Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Implementing custom control structures in Scala (lexandera.com)
15 points by nimbix on Nov 11, 2009 | hide | past | favorite | 5 comments


Tcl is quite good at that sort of thing too:

http://wiki.tcl.tk/685

Because everything is a command.

I have a question though.. what's the 'Unit'? That's how they're passing in a block of code, but http://www.scala-lang.org/docu/files/api/scala/Unit.html doesn't seem to have much information.


Unit is Scala's void. Basically. It's the type returned by functions which don't have a return value.


Ah, I misunderstood then, that's the return type. What type is 'code' and how does it work that you can just put it on a line all its own and it runs? I get that it's figuring out the type via type inference, I'm just curious what the 'magic properties' are.


'code' is actually a function. But because it doesn't take any parameters it's called without '()' at the end.


Actually, 'code' isn't a function - that would require different syntax for declaration and usage:

  def dont(code: () => Unit) = // ...
  dont { () => println("foo") }
It's actually a lazily-evaluated parameter of type Unit - Scala has optional laziness. This means rather than having to pass in a no-arg anonymous function (which requires the "() => expr" syntax as above) you can just pass an expression, and it's evaluated when (and if) needed instead of when it's passed to the "dont" method.

Laziness is the reason that this looks like a control structure, and not just a regular old higher-order function.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: