When you get started with functional programming (FP) a common question you’ll have is, “What is an effect in functional programming?” You’ll hear advanced FPers use the words effects and effectful, but it can be hard to find a definition of what these terms mean.
I always find it confusing when people claim that the IO monad somehow makes an impure function pure. Frankly, I think that argument does a confusing disservice to people who are trying to learn functional programming (FP).
After yesterday’s Scala nested Option + flatMap/for example, here’s another example of plowing through nested Options with
flatMap. First, start with some nested options:
val o1 = Option(1) val oo1 = Option(o1) val ooo1 = Option(oo1)
Here are those same three lines, with the data type for each instance shown in the comments:
“If it wasn’t for the problem of how to sequence input-output actions correctly, monads probably wouldn’t have appeared in Haskell. But once it was appreciated what they could do, all kinds of other uses quickly followed.”
~ Thinking Functionally with Haskell, Richard Bird
“Monad transformers are not too intuitive, especially in Scala, and are known to produce hard to understand code structure.”
~ Debasish Ghosh, Functional and Reactive Domain Modeling
Summary: In this article I show a couple of ways to extract information from optional fields in your Scala domain models. This example is a little contrived, but if you have a situation where one
Option instance contains one or more other
Options, this article may be helpful.
There are times when you’re creating your domain model when it makes sense to use optional fields in your
case classes. For instance, when you model an
Address, the “second street address” isn’t needed for all people, so making it an optional field makes sense:
While reading the excellent Scala/FP book, Advanced Scala with Cats, I was just reminded that Scala’s
Either class was redesigned in Scala 2.12. Prior to 2.12,
Either was not biased, and didn’t implement
flatMap methods. As the image from the book shows,
Either is redesigned in 2.12 to include those methods, so it can now be used in Scala for-expressions as shown.
(I write about biasing in my book, Learning Functional Programming in Scala.)
This is a page from my book, Functional Programming, Simplified
After I released Version 0.1.2 of this book, I realized that I should state my goals for it more clearly. I don’t want you to buy or read a book that doesn’t match what you’re looking for. More accurately, I don’t want you to be disappointed in the book because your expectations are different than what I deliver. Therefore, I want to state some very clear and measurable goals by which you can judge whether or not you want to buy this book.
As a quick note, if you’re interested in using the IO monad described in this IO Monad for Cats article, here’s the source code for a complete Scala
App based on that article: