portable perspectives

a blog about programming, life, universe and everything

Step the picoframework: bigger, smaller

Some time ago I wrote about the toy web framework for scala I had coded to get a feel for the language.

I improved the code a bit after that, but as I did not blog about it and nobody knew it Alan Dipert got the ball and run with it and now the code evolved into a proper project on github, including tests, build management and code that does much more in funny ways :)

Kudos to him who also kindly asked me to keep the name ;)

I had managed to do some things (e.g. path parameters) but he managed to improve it even more, and has already shown me a couple of tricks I did not imagine. For one, I had coded both get and post by hand, and he had done the same adding put and delete, but I just noticed the updated code with the following trick that allows them to be defined programmatically:

  val List(get, post, put, delete) = protocols map routeSetter 
  private def routeSetter(protocol: String): (String) => (=> Any) => Unit = {
    def g(path: String, fun: => Any) = Routes(protocol) += new Route(path, x => fun.toString)
    (g _).curry
  } 

(If I understand correctly this is a change due to paulp's fork. )

As the namespace between functions and values is (mostly) unified in scala the four functions can be defined with a single step. Notice the nifty usage of pattern matching for variable declarations and of currying to have a two-step operation defining the new Route.

I have the feeling the routeSetter function could be shortened by two lines with

private def routeSetter(protocol: String): (String) => (=> Any) => Unit =
  (path: String)=>((fun: => Any) => Routes(protocol) += new Route(path, x => fun.toString))

but it seems scala does not accept the definition of a by-name value in a function literal (yet?)

scala> val f= (x: =>int) => x
<console>:1: error: identifier expected but '=>' found.
       val f= (x: =>int) => x

Anyway, if you have some spare time, maybe you should fork this project and work a bit on it, I know I already did :)

See all comments

AddThis Social Bookmark Button