juan_gandhi: (VP)
2015-05-10 06:44 pm
Entry tags:

Майер просто объяснил

Вот есть функция f(a:A):B

Ну так как она хз когда вернет что-то, то давайте сделаем из нее cps, как в джаваскрипте шоб. f(a:A, accept: B => Unit): Unit.

Ну а что там много параметров, давайте-ка ее каррируем: f(a:A)(accept:B => Unit): Unit - так же можно ее вызвать наполовину, и получить что-то, что берет акцептора ("обработчика"), и применяет его к результату:

f(a:A): (B => Unit) => Unit

Ну так можно же дать название тому, что мы тут делаем, типу результата f:

f(a:A): Future[B]

Вот вам и фьючерсы.
juan_gandhi: (VP)
2015-04-17 10:06 pm
Entry tags:

типа гист


scala> type λ = Any; type λλ=λ=>λ; type λλλ=λ=>λλ;
defined type alias λ
defined type alias λλ
defined type alias λλλ

scala> val I:λλ = (x:λ)=>x
I: λ => λ = <function1>

scala> val K:λλλ = (x:λ)=>(y:λ)=>x
K: λ => (λ => λ) = <function1>

scala> val S = (x:λλλ)=>(y:λλ)=>(z:λ)=>x(z)(y(z))
S: (λ => (λ => λ)) => ((λ => λ) => (λ => λ)) = <function1>


Понятно, что скала никуда не пустит
juan_gandhi: (VP)
2015-04-08 03:23 pm
Entry tags:

bad code!

Just found in my code:
    OKif (!badStuff.find()) orCommentTheError "Bad code"
juan_gandhi: (VP)
2015-03-20 03:12 pm
Entry tags:

скальная конференция, вкратце

Мартин рассказал, что он хочет не скалу, а haskellator. Ну и рассказал о разных новых удобствах в скале, типовая лямбда, например, все такое, что давно пора.

Ли Майдол рассказал, как flyweight pattern имплементируется в скале, и можно гонять гигабайты только так, главное, объектов не создавать, а на потоках работать.

Йонас Бонэр рассказал, что пора уже адекватно относиться к времени в компьютерных системах. Мутабельность - дебильное изобретение.

Томер Габел из Викса показал, что макросы, как они сейчас употребляются в народе, совершенно не годятся для употребления, так что я еще годик подожду.

Джо Барнес показал, что на скале можно делать кое-какие вычиcления с типами, т.к. пеано можно имплементировать. Ну я эту фигню когда-то и на джаве делал, на интервью.

Рекс Керр стал рассказывать про Грок - как его парсер быстро работает, без комбинаторов; но Рекс оказался психологом по образованию, и глубоко не копает; для него стек-машина - открытие века.

Саша Подхалюзин показал фокусы с имплиситами; похожие задачи попадаются и в других областях - найти единственное подходящее определение, ну и т.д.; убедил меня, что с имплиситами надо быть проще - что нетривиально, то лучше не трогать.

Игнасио Касес и Дэвид Холл рассказали о своем NLP, и как они парсят предложения на английском и потом у них, якобы, функтор из английского в предметную область. Не верю.

Рунар Бьярнасон и Тимоти Перрет рассказали, как они в Верайзоне рассекают, посмеялись над HTTP, Json, Akka, и написали свои сериализаторы и протоколы; выглядит очень красиво (в теории); посмотрим еще.

[livejournal.com profile] xeno_by и Денис Шабалин, на нашем скалабее рассказали, соответственно, про элегантную скаламету и про прикольные фокусы с sun.misc.Unsafe. Мне понравилось. Только народу мало было.

Сидел на воркшопе Майлса Сабина про его HLists - во-первых, публика тупая, как это и обычно в Сан Фрациско, во-вторых, фокус примитивный, и рассусоливать его на целый день как-то мало смысла. Ну только разве как дрессировка лохов на тему игры с типами. Не думаю, что это пригодится в реале. Ну ладно, от ассоциативности избавились (почти), а коммутативность? А идемпотентность? А... неинтересно.

Вечером был доклад Джона Прити на Скала Бее про его трансформационные макросы и one-liners. That's the right stuff! Check it out!
juan_gandhi: (VP)
2015-03-09 11:29 am
Entry tags:

just learned an obvious thing

"There is nothing that can possibly be done in this case. The laws of parametricity say that the signature:

def foo[T]: T

can never be satisfied for all T unless you do something dodgy like throw an exception, or not return at all – ie. something that actually is of type Nothing."
juan_gandhi: (VP)
2015-02-28 09:27 pm
Entry tags:

funny scala question

(from Scala maillist)

"Another, possibly related issue:
class StrangeIntQueue extends Queue[Int]
{
  override def enqueue[Int](x:Int) = {
    println( x * x )
    super.enqueue(x).asInstanceOf[Queue[Int]]
  }
}


This has a problem with the '*' in 'x * x' ... complaint is 'Cannot resolve symbol '*''.

Now *that* is fussy.

What is happening?"
juan_gandhi: (VP)
2015-02-18 09:57 am
Entry tags:

funny error in Scala code

val text = "\n\n\nHEADER\n\ncontent\n\n"
val cleanedup = text.dropWhile("\n"==)


The bug comes from the universality of jvm equality, I'd say.
juan_gandhi: (VP)
2015-01-28 02:45 pm
Entry tags:

changing the style

Looks like Yoda master was writing this monadic stuff

...
    ) andThen
      (element("button") containing "Find EOBs" click()) andThen
    ensureSelector(PdfTableMarker) onError suspiciousError
...
juan_gandhi: (VP)
2015-01-15 06:52 pm

о что Подхалюзин пишет:

scala> def f[T](x:T,y:T=>String) = y(x)
f: [T](x: T, y: T => String)String

scala> f("text", s=>s+s)
:9: error: missing parameter type
              f("гав", s=>s+s)
                        ^

scala> def f[T](x:T)(y:T=>String) = y(x)
f: [T](x: T)(y: T => String)String

scala> f("гав")(s=>s+s)
res1: String = гавгав


src: http://www.slideshare.net/AlexanderPodkhalyuzin/under-the-hood-of-scala-implicits-scala-exchange-2014?utm_source=slideshow&utm_medium=ssemail&utm_campaign=upload_digest

Короче, для менеджмента:
если у функции только один параметр, то скала бодро определит ее тип, а если больше, то бывают проблемы ("у нас тут не хиндли и не милнер).

Для CEO: все должны срочно всê каррировать, это теперь паттерн такой.
juan_gandhi: (VP)
2015-01-12 11:34 am
Entry tags:

funny code I found

  def toSource(x: Any): String = {
    x match {
      case null => "null"
      case s: String => "\"" + s.replaceAll("\"", "\\\"") + "\""
      case list:List[_] => "List(" + list.map(toSource).mkString(", ") + ")"
      case array:Array[_] => "Array(" + array.map(toSource).mkString(", ") + ")"
      case map:Map[_, _] => "Map(" + map.map{case(k,v) => toSource(k) + "->" + toSource(v)}.mkString(", ") + ")"
      case other => other.toString
    }
  }
juan_gandhi: (VP)
2015-01-08 01:06 pm
Entry tags:

the joy of Scala for {}

I had a function that was returning a Set[User]; and it was bad, since on error it was returning an empty set, swallowing the error. Bad. So I changed it into something returning Result[Set[User]], which can even show you the stacktrace if needed.

Now the usecase was like this:
  for {
    something <- ...
    somethingElse <- ...
    users = giveMeUsers(something)
    ...
  } yield results


To refactor, I just had to replace '=' with '<-'.

  for {
    something <- ...
    somethingElse <- ...
    users <- giveMeUsers(something)
    ...
  } yield results
juan_gandhi: (VP)
2014-12-13 10:31 pm
Entry tags:

draft scala coding style guide

1. Scala is a mixed object-oriented and functional language. You are free to mix these two features as long as you can explain how it works.
2. Ideally, your code should take care of all possible outcomes. Imagine, it throws an IndexOutOfBounds exception, and somewhere up the food chain some kind of client has to figure out who was it that went outside the range of its data, and why, and what can be done about it, except writing something to the log, so that admins send an email to a manager, and the managers bugs the developer, a day or two later. And you will be scratching your head: who was that bad guy that gave you an empty array when you so desperately needed the array's first element. Since you already know this can happen, you can add the code that takes care of this.
3. Do not:
- use nulls (ask me if you don't know how);
- use vars (ask me if you don't know how);
- introduce setters and getters;
- use mutables (ask me if you don't know how);
- throw exceptions (ask me if you don't know how);
- write methods more than 50 lines long (ideally, more than 14 lines long);
- think this is java;
- hesitate to use more space characters than compiler wants you to;
- except in rare occasions, use indexes of lists, even writing list(0) is bad;
- except for very technical reasons, use length

4. The following are pairs of distinct entities:
- sets and lists;
- order and sequence;
- maps and lists of pairs
5. The code you write will be read by compiler and by your colleague.
5.1. To make compiler's life easy, you can specify the types of your values and functions; it's a known fact that scalac runs faster when types are specified.
5.2. The same applies to your colleagues: if the type of a value is explicitly written (and not obvious otherwise), they'll feel more comfortable;
5.3. Introduce intermediate variables with good names: your compiler may need them, your colleague too.
5.4. Make methods do just one thing.
5.5. There are two kinds of zero-parameter methods: those that just return something with no side effect, and those that mostly just have a side effect, e.g. myInvestment.currentValue vs myInvestment.rebalance().
6. A function that returns a function is okay, it's called currying, and it may also save your cycles (as if anybody cares these days).
7. Your code is a piece of graphic art, although it's just an ASCII art; the more space characters, the more readable it is.
8. The line length... it's up to you, but remember, others are trying to read your masterpiece.
9. Nobody reads documentation or comments these days. So a self-explanatory code makes a lot of sense.
10. Within a project, it may make sense to use the established naming conveniences, coding style and libraries... on the other hand, if we did that, we would be still coding in machine codes and sitting around fire in the caves.
11. Learn local libraries.
12. If you don't know how to write unittests in Scala, drop everything and learn it first. Hardly any of your code makes any sense (even if you believe it does) if there are no tests that prove it (to others; we know you trust yourself). Test frameworks used may vary from project to project; it's a stupid idea to have two frameworks in one project.
13. DRY. Abstraction is your friend.
14. The only true law is that which leads to freedom.


=============
Suggestions?