Created
May 3, 2016 07:23
-
-
Save MatthewJA/2b116b1f09f2662b135d37dfa0c36117 to your computer and use it in GitHub Desktop.
Haskell case pattern matching example
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
data Colour = Red | Green | Blue | Yellow | |
data Shape = Skinny | Round | Triangular | |
data Fruit = Apple | Banana | Strawberry | |
data Appearance = Appearance { colour :: Colour, shape :: Shape } | |
defruitify :: Fruit -> Appearance | |
defruitify fruit = case fruit of | |
Apple -> Appearance { colour = Red, shape = Round } | |
Banana -> Appearance { colour = Yellow, shape = Skinny } | |
Strawberry -> Appearance { colour = Red, shape = Triangular } | |
fruitify :: Appearance -> Maybe Fruit | |
fruitify appearance = case appearance of | |
Appearance { colour = Red, shape = Round } -> Just Apple | |
Appearance { colour = Red, shape = Triangular } -> Just Strawberry | |
Appearance { colour = Yellow, shape = _ } -> Just Banana -- Anything yellow is a banana, right? | |
_ -> Nothing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Far from idiomatic but a simple contrived example nevertheless.