Created
July 29, 2014 03:20
-
-
Save acfoltzer/52055b418ef984e91faf to your computer and use it in GitHub Desktop.
Examples from Haskell Office Hours
This file contains hidden or 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
{-# LANGUAGE FlexibleInstances #-} | |
-- | A simple datatype similar to 'Bool' | |
data A = B | C | |
a :: A | |
a = B | |
-- | A more complicated datatype with values associated with each constructor. | |
data Foo = Bar Int String | Baz (Bool -> Bool) | |
deriving (Show) | |
-- | Since we don't know how to 'show' '(Bool -> Bool)' values by default, we have to | |
-- provide an instance so that we can derive 'show' for 'Foo' | |
instance Show (Bool -> Bool) where | |
show _ = "#<procedure (Bool -> Bool)>" | |
f :: Foo -> String | |
f (Bar 5 "hello") = "hello" | |
f (Bar x "hello") = show x | |
f (Bar x s) = s | |
f (Baz f) = show (f True) | |
-- | A list of integers. Note that 'IntList' appears in its own definition; | |
-- it is a recursive type. | |
data IntList = Nil | Cons Int IntList | |
deriving (Show) | |
ls = Cons 5 (Cons 3 Nil) | |
sumIntList :: IntList -> Int | |
sumIntList Nil = 0 | |
sumIntList (Cons h t) = h + (sumIntList t) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment