Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Second Monad Law:Unit

I am reading James Iry's blog post on Monads in scala. I am in part three and I am confused about his description of the second law of monads regarding Unit. Specifically this claim:

 unit(x) flatMap f = f(x)

When I apply my mental examples which are jame's previous examples of monadic types this never seems to work out

 val x = 1
 val f = (_:Int) * 2
 f(x) == 2 //true
 List(x) flatMap f == 2 //fail
 Some(x) flatMap f == 2 //fail

As a matter of fact they don't even compile due to type issues.

To clarify I understand why these are failing. I understand the how to fix them so they compile.

My confusion is that these seem to be in conflict with the theory presented in the article. Is there a step I am missing? Are these types not really monads? Is the section entitled "Second Law of Monads:Unit" incorrect?

like image 227
nsfyn55 Avatar asked Dec 03 '22 03:12

nsfyn55


1 Answers

Scala's flatMap needs a function that returns a collection, not a function that returns a single element, like your function f.

Either use map:

List(x) map f

or make your function return a collection:

val f = (x: Int) => List(x * 2)

List(x) flatMap f

Note that it will also return a collection, not a single integer (you'll get List(2), not just 2).

like image 150
Jesper Avatar answered Dec 31 '22 10:12

Jesper