Skip to content

Instantly share code, notes, and snippets.

@acfoltzer
Created July 29, 2014 03:20
Show Gist options
  • Save acfoltzer/52055b418ef984e91faf to your computer and use it in GitHub Desktop.
Save acfoltzer/52055b418ef984e91faf to your computer and use it in GitHub Desktop.
Examples from Haskell Office Hours
{-# 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