juan_gandhi: (VP)
2013-07-16 04:26 pm
Entry tags:

scala option map fuckup

scala> def f(x:String) = null
f: (x: String)Null

scala> Some("abc") map f
res3: Option[Null] = Some(null)
juan_gandhi: (VP)
2013-07-15 01:19 pm
Entry tags:

(not so) dirty secrets of Scala

(from Predef:)
  sealed abstract class <:<[-From, +To] extends (From => To) with Serializable
  private[this] final val singleton_<:< = new <:<[Any,Any] { def apply(x: Any): Any = x }
  implicit def conforms[A]: A <:< A = singleton_<:<.asInstanceOf[A <:< A]


Funny. Almost obvious. And interferes with my plans to pass an implicit argument that has an implicit value of an identity function. Because it clashes with "conform", and if I shadow "conform", nothing will compile in that class.
juan_gandhi: (VP)
2013-07-15 11:12 am
Entry tags:

hocon

hocon per se is a good stuff; but Typesafe's implementation, Config, is not something I feel happy with.

First, it is JAVA!!!!
Second, where's "getOrElse"? getInt could have a default value, right? Or a default Option value, which is better. Or have a lift that would be returning an option
Third, how about ++ and the like?
Fourth, what is this:
public enum ConfigValueType {
OBJECT, LIST, NUMBER, BOOLEAN, NULL, STRING
}


This is also funny:
    @Override
    public Long getMilliseconds(String path) {
        long ns = getNanoseconds(path);
        long ms = TimeUnit.NANOSECONDS.toMillis(ns);
        return ms; 
    }

    @Override
    public Long getNanoseconds(String path) {
        Long ns = null;
        try {
            ns = TimeUnit.MILLISECONDS.toNanos(getLong(path));
        } catch (ConfigException.WrongType e) {
            ConfigValue v = find(path, ConfigValueType.STRING);
            ns = parseDuration((String) v.unwrapped(), v.origin(), path);
        }
        return ns;
    }


In short, I'm thinking of abandoning it. Might make sense to write our own stuff, I don't know. So far my Props work well.
juan_gandhi: (VP)
2013-07-13 08:54 am
Entry tags:

v2

Tweaked it a little bit... seems like cannot make it smaller any further; pity.

https://gist.github.com/vpatryshev/ca5a1bfdaf00d2481a0c
juan_gandhi: (VP)
2013-07-12 06:34 pm
Entry tags:

nice scala

deep copy done easily
object Example {
  trait Nested[A] { def dup: A => A }
  object Nested {
    implicit def nestedAnything[A] = new Nested[A] { def dup = identity }
    implicit def nestedArray[A](implicit ev: Nested[A], mf: Manifest[A]) = 
      new Nested[Array[A]] { def dup = _ map ev.dup }
  }
  def deepDup[A](aa: Array[A])(implicit ev: Nested[Array[A]]) = ev dup aa
}

scala> val a = Array(Array(1,2,3), Array(4,5,6), Array(7,8))
a: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8))
scala> val c = deepDup(a)
c: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8))
scala> a(0)(0)=9; c // it's a copy, not a reference
res0: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8))



questions? improvements?
juan_gandhi: (VP)
2013-07-10 02:38 pm
Entry tags:

mutability: butterfly effect

scala> import collection.mutable.Queue
import collection.mutable.Queue

scala> val m: Map[Int, Queue[Int]] = Map().withDefaultValue(Queue[Int]())
m: Map[Int,scala.collection.mutable.Queue[Int]] = Map()

scala> m(0)
res0: scala.collection.mutable.Queue[Int] = Queue()

scala> m(0).enqueue(1)

scala> m(1)
res2: scala.collection.mutable.Queue[Int] = Queue(1)
juan_gandhi: (VP)
2013-07-08 04:11 pm
Entry tags:

funny discovery

"abc" map { case 'a' => "A"; case x => x }
juan_gandhi: (VP)
2013-07-07 09:42 am
Entry tags:

just learned

case classes in Scala have a method copy

Neat, nice, nifty!

Now the question is: why would one need it, in case the class is immutable?!

This is why
  case class Person(first: String, second: String)
  val p1 = Person("John", "Waters")
  val p2 = p1.copy(first="James")
juan_gandhi: (VP)
2013-07-04 10:12 pm
Entry tags:

videobook, kind of

http://www.programmingusingscala.net/home/chapters

Many chapters represented as video talks by the author.
juan_gandhi: (VP)
2013-05-20 06:00 pm
Entry tags:

about exceptions in jvm

Seems like scala people look down at exceptions... but see. The difference between an error message and an exception is that an exception tells you where the error happened. I actually use it in pretty unusual places, like this:
def jsREPL(implicit prompt:String = "type your js") {
  val here = Thread.currentThread().getStackTrace()(3)
  println(s"$prompt [${here.getFileName}:${here.getLineNumber}]: ")
  Source.fromInputStream(System.in).getLines.takeWhile(!_.isEmpty) foreach {
    s => println(tryOr(runJS(s), (_:Exception).getMessage))
  }


What I want to say: if we, in Scala, had a habit of passing around exceptions, instead of plain text, it would be pretty helpful.

Thinking about it.
juan_gandhi: (VP)
2013-05-10 01:01 pm
Entry tags:

now tell me...

Scala existential types, are they factortypes, are they not? Coequalizers, function images, like that.
juan_gandhi: (VP)
2013-05-08 05:39 pm
Entry tags:

a prayer

can anybody please please please add val to JavaScript?!!!!!
juan_gandhi: (VP)
2013-04-28 07:15 pm
Entry tags:

котята, блин

Сегодня приходили за котятами - а я не смог поймать. Они сделали подкоп под кухню, и прячутся туда если чо.

О как сложна жизнь.

Другая тема - это надо что-то делать с кодом типа такого:

 result match {
   case Good(something) =>
     something match {
       case arr: Array[(String, String)] => println(s"aint that something ${arr mkString ", "})
       case x => error(s"bad, bad response pretending to be good: $result")
     }
   case noGood => error(s"no good! $result)
 }


This still causes a (rightful) warning, and I don't see (yet) how I can fix it all without being absolutely stupid. It frustrates me, yes. I don't even see a monadic pattern here... neither an app functor. Bad, bad.
juan_gandhi: (VP)
2013-03-13 11:06 am
Entry tags:

some obvious stuff

  def tryOr  [T](eval: =>T, onError: Exception => T) =
    try { eval } catch { case e: Exception => onError(e) }

  def tryOr  [T](eval: =>T, orElse: T) =
    try { eval } catch { case e: Exception => orElse }

  def attempt[T](eval: =>T): Option[T] = tryOr(Option(eval), None)

  class BetterArray[T](array: Array[T]) {
    def get(i: Int): Option[T] = attempt(array(i))
    def getOrElse(i: Int, defaultValue: T) = get(i) getOrElse defaultValue
  }

  implicit def elementOf[T](array: Array[T]) = new BetterArray[T](array)


questions?
juan_gandhi: (VP)
2013-02-28 10:50 pm
Entry tags:

а вот простой пример как из джавного ArrayList сделать функтор на коленке

Идея: есть джавный java.util.ArrayList, древний как доткомовский бум. А мы хочем функтор, но не можем написать ArrayList extends Functor; ну дык... дык и хер с ним; мы ж инженеры. В Скале можно. А зачем? А чтобы писать arrayList.map(someting=>something)
И в продакшен. Мы же инженеры!

gist


Могу написать подробные комментарии, если интересно.
juan_gandhi: (VP)
2013-02-20 01:51 pm
Entry tags:

dumping stuff from stream to file fast

      val out = new FileOutputStream(myFile).getChannel
      val in: InputStream = sampleResourcePdfBSBCTX.openStream
      val ch = Channels.newChannel(in)
      try {
        while (true) {
          val nBytes = in.available
          out.transferFrom(ch, out.position, nBytes)
          out.position(out.position + nBytes)
        }
      } finally { out.close() }
      val text = PDF.extractTextFromImagesHiddenInPdf(pdf)
      text contains "Claim No.: 30l8507l5lSOX" mustBe true
    }
  }