Reputation: 41939
Working through Functional Programming in Scala, the book shows the Gen Monad
definition. Gen, as I understand, is a ScalaCheck trait.
val genMonad = new Monad[Gen] {
def unit[A](a => A): Gen[A] = Gen.unit(a)
def flatMap[A, B](ma: Gen[A])(f: A => Gen[B]) =
ma.flatMap(f)
}
I believe that OptionMonad.unit
is defined as Some(a)
, but I don't understand Gen.unit(a)
.
How is Gen.unit(a)
defined?
Upvotes: 1
Views: 126
Reputation: 20515
A Gen[A]
is just an object which can be repeatedly called to give instances of type A
. These "generators" are used to drive the ScalaCheck automated testing framework, which lets programmers specify properties of objects of a given type, and then repeatedly generates instances of that type and checks those properties. Gen forms a monad, which is to say it supports the operations of "unit" and "bind", about which approximately a zillion tutorials can be found on the internet. Scala's idioms for monads are a bit inconsistent, as monad types have a standard method of bind
, called flatMap
, but none for unit
. This is because Scala is object oriented, and unit
doesn't take an object of it's monad, but instead returns one, so it doesn't make any sense to make unit
a method of the underlying class. Instead, most Scala monads leave the unit
method implicit, often as a single-element constructor of the monad type.
So with that background out of the way, what's unit
of Gen[A]
. Well it needs to be something which takes an object of type A
as an argument, and then allows repeated generation of objects of type A
. Since A
could literally be anything, there's really only one thing we can come up with which fits this bill. unit(a)
must be a boring generator which repeatedly returns a
. Simple once you think it through.
Upvotes: 2