Id Monad

The same way Option encodes optionality, the Id represents nothing special. It wraps a value but does nothing with it. Why would we need something that's not a thing? The Id is kind of a meta-lifting, which can represent anything as an effect without changing it. How can this be done? Well, first of all, we have to say to the compiler that an Id[A] is the same thing as an A. This is easily done with a type alias:

type Id[A] = A

This type definition will dictate the details of the monad's implementation:

implicit val idMonad = new Monad[Id] {
override def unit[A](a: => A): Id[A] = a
override def flatMap[A, B](a: Id[A])(f: A => Id[B]): Id[B] = f(a)
}

Obviously, unit(a) is just a, and by having the type alias we just defined, we're making the compiler believe that it is not of type A, but an Id[A]. Similarly, with the flatMap, we can't do anything fancy, so we're just applying the given function f to a, utilizing the fact that Id[A] is actually just A.

Obviously, as we're doing nothing, the monadic laws should hold. But just to be 100% sure, we'll encode them as properties:

property("Monad[Id] and Int => String, String => Long") = {
monad[Int, String, Long, Id]
}
property("Monad[Id] and String => Int, Int => Boolean") = {
monad[String, Int, Boolean, Id]
}
+ Monad.Monad[Id] and Int => String, String => Long: OK, passed 100 tests.
+ Monad.Monad[Id] and String => Int, Int => Boolean: OK, passed 100 tests.

The property holds—what else would you expect from something that does nothing? But why do we need this something in the first place? 

This question has multiple answers. From an abstract perspective, the Id monad carries the function of (surprise!) an identity element in the space of monads in the same way that zero or one are the identity elements in the space of numbers under addition or multiplication. Because of this, it can be used as a placeholder for monad transformers (we'll learn about them in the next chapter). It can also be useful in a situation where in existing code expects a monad but we don't need one. We will see how this approach works later in this chapter.

Now that we have got our feet wet with the simplest monad, it is time to do something more involvingimplementing the State monad.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.191.134