Skip to content

Instantly share code, notes, and snippets.

@YoEight
Created July 27, 2012 13:14
Show Gist options
  • Save YoEight/3187848 to your computer and use it in GitHub Desktop.
Save YoEight/3187848 to your computer and use it in GitHub Desktop.
Maybe monad as a continuation
object maybeExample {
sealed trait Maybe[A]{ self =>
def fold[Z](just: A => Z, nothing: => Z): Z
def map[B](f: A => B) = fold(a => Just(f(a)), Nothing[B])
def flatMap[B](f: A => Maybe[B]) = new Maybe[B]{
def fold[Z](just: B => Z, nothing: => Z) =
self.fold(a => f(a).fold(just, nothing), nothing)
}
override def toString = fold(a => "Just(" + a.toString + ")", "Nothing")
}
object Just {
def apply[A](v: => A) = new Maybe[A]{
def fold[Z](just: A => Z, nothing: => Z) = just(v)
}
}
object Nothing {
def apply[A] = new Maybe[A]{
def fold[Z](just: A => Z, nothing: => Z) = nothing
}
}
def mul(m1: Maybe[Int], m2: Maybe[Int]): Maybe[Int] = for {
x <- m1
y <- m2
} yield x * y
def test = mul(Just(3), Just(2)) // Just(6)
def test2 = mul(Just(3), Nothing[Int]) // Nothing
}
{-# LANGUAGE RankNTypes #-}
module Option where
newtype Option a = Option (forall r. (a -> r) -> r -> r)
option :: Option a -> (a -> r) -> r -> r
option (Option k) = k
some :: a -> Option a
some a = Option (\f _ -> f a)
none :: Option a
none = Option (\_ d -> d)
instance Show a => Show (Option a) where
show o = option o (\a -> "Some(" ++ (show a) ++ ")") "None"
instance Monad Option where
return = some
m >>= f = Option (\onSome onNone -> option m (\a -> option (f a) onSome onNone) onNone)
mul :: Option Int -> Option Int -> Option Int
mul o o'= do
x <- o
y <- o'
return $ x * y
test = mul (some 3) (some 2) -- Some(6)
test2 = mul (some 3) none -- None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment