Skip to content

Instantly share code, notes, and snippets.

@imeredith
Forked from tonymorris/Applicative.scala
Created July 28, 2012 03:25
Show Gist options
  • Save imeredith/3191634 to your computer and use it in GitHub Desktop.
Save imeredith/3191634 to your computer and use it in GitHub Desktop.
Applicative exercise
object Applicative {
// pick any monad, I have picked Option for you
type F[A] = Option[A]
// Applicative primitive given concrete
// AKA point, pure, return
def lift0[A](a: A): F[A] =
Some(a)
// Applicative primitive given concrete
// AKA <*>
def ap[A, B](f: F[A => B]): F[A] => F[B] =
a => f flatMap (ff => a map (ff(_)))
// Implement using lift0 + ap
// AKA map
def lift1[A, B](f: A => B): F[A] => F[B] =
ap(lift0(f))
// Implement using:
// lift1 + ap
def lift2[A, B, C](f: A => B => C): F[A] => F[B] => F[C] =
(a) => ap(lift1(f)(a))
// Implement using:
// lift2 + ap
def lift3[A, B, C, D](f: A => B => C => D): F[A] => F[B] => F[C] => F[D] =
(a) => (b) => ap(lift2(f)(a)(b))
// Implement using:
// lift3 + ap
def lift4[A, B, C, D, E](f: A => B => C => D => E): F[A] => F[B] => F[C] => F[D] => F[E] =
(a) => (b) => (c) => ap(lift3(f)(a)(b)(c))
// Implement using:
// lift4 + ap
def lift5[A, B, C, D, E, G](f: A => B => C => D => E => G): F[A] => F[B] => F[C] => F[D] => F[E] => F[G] =
(a) => (b) => (c) => (d) => ap(lift4(f)(a)(b)(c)(d))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment