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

scala> Some("abc") map f
res3: Option[Null] = Some(null)
juan_gandhi: (VP)
(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.

hocon

Jul. 15th, 2013 11:12 am
juan_gandhi: (VP)
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.

v2

Jul. 13th, 2013 08:54 am
juan_gandhi: (VP)
Tweaked it a little bit... seems like cannot make it smaller any further; pity.

https://gist.github.com/vpatryshev/ca5a1bfdaf00d2481a0c

nice scala

Jul. 12th, 2013 06:34 pm
juan_gandhi: (VP)
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)
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)
"abc" map { case 'a' => "A"; case x => x }
juan_gandhi: (VP)
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)
http://www.programmingusingscala.net/home/chapters

Many chapters represented as video talks by the author.
juan_gandhi: (VP)
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)
Scala existential types, are they factortypes, are they not? Coequalizers, function images, like that.

a prayer

May. 8th, 2013 05:39 pm
juan_gandhi: (VP)
can anybody please please please add val to JavaScript?!!!!!
juan_gandhi: (VP)
Сегодня приходили за котятами - а я не смог поймать. Они сделали подкоп под кухню, и прячутся туда если чо.

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

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

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

gist


Могу написать подробные комментарии, если интересно.
juan_gandhi: (VP)
      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
    }
  }

Profile

juan_gandhi: (Default)
Juan-Carlos Gandhi

November 2025

S M T W T F S
       1
23456 7 8
9 1011 12 1314 15
16171819 20 2122
23 24 252627 28 29
30      

Syndicate

RSS Atom

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Nov. 30th, 2025 07:52 pm
Powered by Dreamwidth Studios