Created
January 10, 2015 11:00
-
-
Save saeidw/5bb56505ed3371ce6b8c to your computer and use it in GitHub Desktop.
Sum types with functions
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
-- 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