Created
April 27, 2015 14:28
-
-
Save grzegorzbalcerek/8944fd2c86a91d429254 to your computer and use it in GitHub Desktop.
Monad Exercises Solutions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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