Skip to content

Instantly share code, notes, and snippets.

@qzchenwl
Created September 13, 2011 11:54
Show Gist options
  • Save qzchenwl/1213655 to your computer and use it in GitHub Desktop.
Save qzchenwl/1213655 to your computer and use it in GitHub Desktop.
import Control.Monad
import Data.Maybe
maybeToMonad :: (MonadPlus m) => Maybe a -> m a
maybeToMonad Nothing = mzero
maybeToMonad (Just x) = return x
type Sheep = Int
father :: Sheep -> Maybe Sheep
father 1 = Just 2
father 2 = Just 4
father 3 = Just 11
father 5 = Just 12
father _ = Nothing
mother :: Sheep -> Maybe Sheep
mother 1 = Just 3
mother 2 = Just 5
mother 3 = Just 10
mother _ = Nothing
parent2 :: Sheep -> Maybe Sheep
parent2 s = (mother s) `mplus` (father s)
grandparent2 :: Sheep -> Maybe Sheep
grandparent2 s = (parent2 s) >>= parent2
parent3 :: Sheep -> [Sheep]
parent3 s = (maybeToList $ mother s) `mplus` (maybeToList $ father s)
grandparent3 :: Sheep -> [Sheep]
grandparent3 s = (parent3 s) >>= parent3
parent4 :: (MonadPlus m) => Sheep -> m Sheep
parent4 s = (maybeToMonad $ mother s) `mplus` (maybeToMonad $ father s)
grandparent4 :: (MonadPlus m) => Sheep -> m Sheep
grandparent4 s = (parent4 s) >>= parent4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment