Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Monad Exercises Solutions
import language.higherKinds
trait Monad1[M[_]] {
def id[A](a: A): M[A]
def compose[A,B,C](f: A => M[B], g: B => M[C]): A => M[C]
def flatMap[A,B](ma: M[A], f: A => M[B]): M[B] =
compose((_:Unit) => ma, f)(())
def join[A](mma: M[M[A]]): M[A] =
flatMap(mma, identity[M[A]])
def ap[A,B](ma: M[A], mab: M[A => B]): M[B] =
flatMap(ma, (a:A) =>
flatMap(mab, (f:A=>B) =>
id(f(a))))
def map[A,B](ma: M[A], f: A => B): M[B] =
ap(ma, id(f))
}
import language.higherKinds
trait Monad2[M[_]] {
def id[A](a: A): M[A]
def flatMap[A,B](ma: M[A], f: A => M[B]): M[B]
def compose[A,B,C](f: A => M[B], g: B => M[C]): A => M[C] =
(a:A) => flatMap(f(a),g)
def join[A](mma: M[M[A]]): M[A] =
flatMap(mma, identity[M[A]])
def ap[A,B](ma: M[A], mab: M[A => B]): M[B] =
flatMap(ma, (a:A) =>
flatMap(mab, (f:A=>B) =>
id(f(a))))
def map[A,B](ma: M[A], f: A => B): M[B] =
ap(ma, id(f))
}
import language.higherKinds
trait Monad3[M[_]] {
def id[A](a: A): M[A]
def map[A,B](ma: M[A], f: A => B): M[B]
def join[A](mma: M[M[A]]): M[A]
def flatMap[A,B](ma: M[A], f: A => M[B]): M[B] =
join(map(ma,f))
def compose[A,B,C](f: A => M[B], g: B => M[C]): A => M[C] =
(a:A) => flatMap(f(a),g)
def ap[A,B](ma: M[A], mab: M[A => B]): M[B] =
flatMap(ma, (a:A) =>
flatMap(mab, (f:A=>B) =>
id(f(a))))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment