Skip to content

Instantly share code, notes, and snippets.

@MatthewJA
Created May 3, 2016 07:23
Show Gist options
  • Save MatthewJA/2b116b1f09f2662b135d37dfa0c36117 to your computer and use it in GitHub Desktop.
Save MatthewJA/2b116b1f09f2662b135d37dfa0c36117 to your computer and use it in GitHub Desktop.
Haskell case pattern matching example
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
@MatthewJA
Copy link
Author

Far from idiomatic but a simple contrived example nevertheless.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment