Skip to content

Instantly share code, notes, and snippets.

@xfire
Created July 2, 2010 15:30
Show Gist options
  • Save xfire/461518 to your computer and use it in GitHub Desktop.
Save xfire/461518 to your computer and use it in GitHub Desktop.
haskell functor examples
data Tree a = Node (Tree a) (Tree a)
| Leaf a
deriving Show
instance Functor Tree where
fmap g (Leaf v) = Leaf (g v)
fmap g (Node l r) = Node (fmap g l) (fmap g r)
sampleTree :: Tree String
sampleTree = Node (Node (Leaf "hello") (Leaf "foo")) (Leaf "baar")
treeToLength :: Tree [a] -> Tree Int
treeToLength t = fmap length t
treeExample :: IO ()
treeExample = do
putStrLn $ show $ sampleTree
putStrLn "-->"
putStrLn $ show $ treeToLength sampleTree
maybeExample :: IO ()
maybeExample = do
putStrLn $ show (Just "foobar")
putStrLn "-->"
putStrLn $ show $ fmap length (Just "foobar")
maybeExample' :: IO ()
maybeExample' = do
putStrLn $ show (Nothing :: Maybe ())
putStrLn "-->"
putStrLn $ show $ fmap length (Nothing)
main = do
let seperator = take 45 $ repeat '-'
treeExample
putStrLn seperator
maybeExample
putStrLn seperator
maybeExample'
putStrLn seperator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment