It’s time to learn Scala. I took Martin Odersky’s course a couple of years ago and thoroughly enjoyed it. Now that some time has passed and I’ve been deeply immersed in all things Haskell, I feel it’s a good time to revisit Scala.
I thought I’d take a look at algebraic data types which is, I believe, something that Haskell excels at.
That’s a lot of typing. “The world’s most verbose sum types”, as someone once said.
But, at least I can pattern-match on it!
Surprisingly, the Haskell version isn’t significantly shorter in terms of line count:
Though there is less line noise.
Here’s another side-by-side comparison of an extension to my simple expression language embedded in an algebraic data type. This adds
Maybe) types to the evaluation function, making this a convenient vehicle for demonstrating how to handle applicative and monadic computations using Scalaz:
The two pieces of code look remarkably similar. Haskell has a much more compact (and, in my opinion, intuitive) way of defining the
Expr sum type. Haskell’s
Applicative (baked into
Prelude) provides the elegance of
<*> but, other than that, they’re clearly similar. The
do-notation is eerily similar, in fact.
All in all, all this
flatMapping etc. makes a lot more sense now that I have Haskell in my veins. Furthermore, Scala’s syntactic noise is tolerable. Given that I primarily write Java at work and Haskell at home, Scala feels like a nice midway point between the two. I am confident that Scala will feel like a nice warm fuzzy comfort blanket one day!
Here’s a translation into Java:
And in OCaml:
All content © 2019 Richard Cook. All rights reserved.