In [ ]:
-- a trivial example of pattern matching
-- in haskell most everyting is an 'expression'
lucky :: (Integral a) => a -> String -- this is the type annotation
lucky 7 = "LUCKY NUMBER SEVEN!"
lucky _ = "Sorry, you're out of luck!"
In [ ]:
lucky 6
lucky 7
lucky 42
In [ ]:
-- factorial function using recursion
fact :: (Integral a) => a -> a
fact 0 = 1 -- this is called the base case / a catch all stopper
fact n = n * fact (n - 1) -- this is called "recursion" because fact refs itself in
In [ ]:
fact 3 --1. fact 3 reduces to 3 * fact (3-1) == fact 2
--2. fact 2 reduces to 2 * fact 1 -- fact (2-1) == fact 1
--3. fact 1 reduces to 1 * fact 0 -- fact 0 = 1 --first pattern
--4. together we end up with:
-- 3 * (2 * (1 * 1)) = 6
In [ ]:
-- Patern matching with Tuples
addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a)
addVectors (x1, y1) (x2, y2)= (x1 + x2, y1 + y2)
In [ ]:
addVectors (30, 33)(12, 9)
In [ ]:
-- Pattern match in list comprehensions this way:
xs = [(1,3), (4,3), (5, 1)]
[a+b | (a,b) <- xs]
In [ ]:
[2,4,6] == 2:4:6:[] --[2,4,6] is syntactic sugar for 2:4:6:[]
In [ ]:
fact 10