Last active
February 28, 2020 19:30
-
-
Save taiansu/25a62fbdc094877f8f5b5c4d9108f19e to your computer and use it in GitHub Desktop.
pattern matching in Haskell
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
module Main where | |
-- data, you can think this is something like {:user, name, age} in Elixir | |
data User = User String Int | |
foo (User "John" _) = 100 | |
foo (User _ age) = age | |
-- tuple | |
bar (_, _, 3) = 100 | |
bar (_, y, z) = y + z | |
-- record syntax | |
data Point = | |
Point { x :: Int | |
, y :: Int | |
, z :: Maybe Int } | |
makePoint = Point {x=0, y=0, z=Nothing} | |
baz :: Point -> (Int, Int) | |
baz Point {x=1, y=y} = (100, 100) | |
baz Point {x=x, y=y} = (x, y) | |
main :: IO () | |
main = do | |
print $ foo (User "John" 20) -- => 100 | |
print $ foo (User "Bob" 20) -- => 20 | |
print $ bar (1, 2, 3) -- => 100 | |
print $ bar (3, 4, 5) -- => 9 | |
print $ baz makePoint {x=1, y=2} -- => (100, 100) | |
print $ baz makePoint {x=3, y=4, z=Just 5} -- => (3, 4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment