1. Pattern matching consists of
3. Order is important when specifying patterns and it's always best to specify the most specific ones first and then the more general ones later.
- factorial :: (Integral a) => a -> a
- factorial 0 = 1
- factorial n = n * factorial (n - 1)
4. Pattern matching can also fail. We should always include a catch-all pattern so that our program doesn't crash if we get some unexpected input.
5. Pattern matching can also be used on tuples.
- addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a)
- addVectors a b = (fst a + fst b, snd a + snd b)
- addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a)
- addVectors (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
The _ means that we really don't care what that part is, so we just write a _.
- first :: (a, b, c) -> a
- first (x, _, _) = x
- second :: (a, b, c) -> b
- second (_, y, _) = y
- third :: (a, b, c) -> c
- third (_, _, z) = z
6. Pattern match in list comprehensions.
- ghci> let xs = [(1,3), (4,3), (2,4), (5,3), (5,6), (3,1)]
- ghci> [a+b | (a,b) <- xs]
- [4,7,6,8,11,4]
Should a pattern match fail, it will just move on to the next element.
7. Pattern match against list
Our own implementation of the head function.
- head' :: [a] -> a
- head' [] = error "Can't call head on an empty list, dummy!"
- head' (x:_) = x
length function using list comprehension
- length' :: (Num b) => [a] -> b
- length' [] = 0
- length' (_:xs) = 1 + length' xs
If we call length' on "ham".
1) It will check if it's an empty list
2) Because it isn't, it falls through to the second pattern. It matches on the second pattern and there it says that the length is 1 + length' "am" → 1 + (1 + length' "m") → 1 + (1+(1+ length' [])) → 1 + (1 + (1 + 0)).
Let's implement sum.
- sum' :: (Num a) => [a] -> a
- sum' [] = 0
- sum' (x:xs) = x + sum' xs
8. @ in front of a pattern
You do that by putting a name and an @ in front of a pattern. For instance, the pattern xs@(x:y:ys). This pattern will match exactly the same thing as x:y:ys but you can easily get the whole list via xs instead of repeating yourself by typing out x:y:ys in the function body again. Here's a quick and dirty example:
- capital :: String -> String
- capital "" = "Empty string, whoops!"
- capital all@(x:xs) = "The first letter of " ++ all ++ " is " ++ [x]
- ghci> capital "Dracula"
- "The first letter of Dracula is D"
본 카테고리의 내용은 Learn You a Haskell for Great Good! 의 내용을 학습을 위해 요약한 것입니다.
'프로그래밍 Programming' 카테고리의 다른 글
Haskell Operators and other Lexical Notation (0) | 2018.03.17 |
---|---|
Haskell_006 Guards (0) | 2018.03.17 |
Haskell_004 Some basic typeclasses - Eq, Ord, Show, Read, Enum, Bounded, and Num (0) | 2018.03.16 |
Haskell Type, Typeclass, and Type variables (0) | 2018.03.16 |
Haskell_ 003 Typeclass (0) | 2018.03.15 |