Created
July 2, 2010 15:30
-
-
Save xfire/461518 to your computer and use it in GitHub Desktop.
haskell functor examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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