Skip to content

Instantly share code, notes, and snippets.

@joshcough
Created December 19, 2011 19:59
Show Gist options
  • Save joshcough/1498625 to your computer and use it in GitHub Desktop.
Save joshcough/1498625 to your computer and use it in GitHub Desktop.
def map[A,B](fa: F[A])(f: A => B): F[B] = bind(fa)(a => unit(f(a)))
def join[A](f: F[F[A]]): F[A] = bind(f)(identity)
def kleisli[A,B](f: A => B): A => F[B] = a => unit(f(a))
def bind2[A,B](fa: F[A])(f: A => F[B]): F[B] = join(map(fa)(f))
def ap[A,B](f: F[A => B])(fa: F[A]): F[B] = bind(f)(fab => map(fa)(fab))
def map2[A,B,C](fa: F[A], fb: F[B])(f: (A,B) => C): F[C] = bind(fa)(a => map(fb)(b => f(a,b)))
def map3[A,B,C,D](fa: F[A], fb: F[B], fc: F[C])(f: (A,B,C) => D): F[D] =
bind(fa)(a => bind(fb)(b => map(fc)(c => f(a,b,c))))
def lift2[A,B,C](f: (A,B) => C): (F[A],F[B]) => F[C] = (fa,fb) => map2(fa,fb)(f)
def cons[A](a:A)(as:List[A]) = a :: as
def sequence[A](fas: List[F[A]]): F[List[A]] = fas match {
case Nil => unit(Nil)
case x :: xs => ap(map(x)(cons))(sequence(xs))
}
def traverse[A,B](fas: List[A])(f: A => F[B]): F[List[B]] = sequence(fas.map(f))
// TODO: re-read applicative chapter in LYAH
// TODO: write sequence with fold
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment