Skip to content

Instantly share code, notes, and snippets.

@taiansu

taiansu/Main.hs

Last active Feb 28, 2020
Embed
What would you like to do?
pattern matching in Haskell
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
You can’t perform that action at this time.