Slides for the sixth lesson in my PureScript lunch-n-learn series. This lesson takes a closer look at pattern matching, starting at the top of chapter 5 of "PureScript by Example."
-> Array a -> Int count = count' 0 where count' acc _ [] = acc count' acc p xs = count' (acc + (if p (unsafePartial head xs) then 1 else 0)) p (unsafePartial tail xs)
"true" = true stringToBool _ = false boolToString :: Boolean -> String boolToString true = "true" boolToString false = "false" Can match on literal values _ is a special wildcard to match any value without binding a name
:: Int -> Int -> Int gcd' n 0 = n gcd' 0 m = m gcd' n m | n > m = gcd' (n - m) m | otherwise = gcd' n (m - n) Guards use `|` to place additional constraints on the case
:: Int -> Int -> Int gcd' n 0 = n gcd' 0 m = m gcd' n m | n > m = gcd' (n - m) m | otherwise = gcd' n (m - n) Guards use `|` to place additional constraints on the case Special keyword to match anything else
_] = a * b takeFive _ = 0 > takeFive [0, 1, 2, 3, 4] 6 > takeFive [1, 2, 3, 4, 5] 0 First case matches all arrays of exactly 5 values, where the first 2 values are 0, 1
_] = a * b takeFive _ = 0 > takeFive [0, 1, 2, 3, 4] 6 > takeFive [1, 2, 3, 4, 5] 0 > takeFive [] 0 First case matches all arrays of exactly 5 values, where the first 2 values are 0, 1
:: String } -> String showPerson { first: x, last: y } = y <> ", " <> x Matches records that, at a minimum, contain first and last properties Binds those properties to names
sortPair arr@[x, y] | x <= y = arr | otherwise = [y, x] sortPair arr = arr Any pattern may be “named” by using the @ symbol Matches arrays with two elements
sortPair arr@[x, y] | x <= y = arr | otherwise = [y, x] sortPair arr = arr Any pattern may be “named” by using the @ symbol Matches arrays with two elements Because of the named pattern, only this case allocates a new array in memory