Skip to content

Instantly share code, notes, and snippets.

@saeidw
Created January 10, 2015 11:00
Show Gist options
  • Save saeidw/5bb56505ed3371ce6b8c to your computer and use it in GitHub Desktop.
Save saeidw/5bb56505ed3371ce6b8c to your computer and use it in GitHub Desktop.
Sum types with functions
-- We can have a sum type where each constructor is a function:
data F = A (String -> Int)
| B (Int -> Int)
-- Now let's create a value of this type:
-- The `length` function has type `[a] -> Int` and since
-- `String` is a synonym for `[Char]` we can use `length` on strings
f :: F
f = A (length)
g :: F
g = B (+1)
-- How do we use a function of type F?
testF :: F -> Int
testF f = case f of
A a -> a "hello world"
B b -> b 5
testF f
-- Result: 11
testF g
-- Result: 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment