An algebraic data type in Scala


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.

Update: 2019-02-20

Here’s another side-by-side comparison of an extension to my simple expression language embedded in an algebraic data type. This adds Option (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 <$> and <*> but, other than that, they’re clearly similar. The flatMap/for-comprehension vs. 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!

Update: 2019-02-20

Here’s a translation into Java:

Update: 2019-02-23

And in OCaml:

Related posts

My first Eta program
LambdaConf 2016 conference report
My first MOOC: “Functional Programming Principles in Scala”



Content © 2024 Richard Cook. All rights reserved.