Monday 30 April 2012

Validation without Scalaz

[2012-05-01 Update: added snippets showing case where check functions are in a collection.]
[2012-05-06 Update: links now point to new branch, 'simple' instead of 'master' one.]

So it's the desire to implement checks (that inputs are valid) in a more functional way (than by throwing exceptions) that's one of the main motivations for adopting Scalaz, it seems.

I've encountered evidence for this on at least a couple of occasions: first, at Chris Marshall's talk about practical uses of Scalaz in the financial industry at Skills Matter, and most recently, at Noel Welsh's Blue Eyes presentation at Scala Days 2012.

Having played around with the standard Scala library's scala.Either myself recently, after Noel's talk, I got to asking a few people why more use wasn't made of that.

Apparently, this is because Either can't be used in for comprehensions involving multiple generators (since it lacks a flatMap method), and because there's no support for accumulating bad results.

So I've since taken a closer look, and discovered that it can in fact be used in said for comprehensions, and that with the help of this twenty-odd line type-class, can also be used to accumulate bad results!

The challenge I set myself was to try to rewrite Chris's (very helpful) Nightclubs (Github) gist without using Scalaz. This I succeeded in doing, as shown here.

The trick is to use the Either's right: RightProjection method in for comprehensions. So this...


...becomes this:


And Chris's code for accumulate bad values...



...may be rewritten using an implicit method provided by the type class:


Finally, if the checks happen to be in a collection, this...


...becomes this:



Please help yourself to the type class, which is maintained in a Github project called scala-either-extras.

Comments welcome.