There was already some pattern matching explained, in the context of bindings here. Here we explain pattern matching in other contexts, which are:
Before we start with that, we provide more details about pattern matching, regarding:
Additionally, even before that we explain the wildcard _.
_main :: IO ()
main =
do
print (firstFromTuple3 ("A",'b','c'))
print (secondFromList "Hallo!")
print (getZipFromPerson (PersonNameZipAndEMail "Haskell" "Brooks" "Curry" 16802 "hbc@psu.edu"))
firstFromTuple3 :: (a,b,c) -> a
firstFromTuple3 (x,_,_) = x
secondFromList :: [a] -> a
secondFromList (_:x:_) = x
data Person = PersonNameAndZip String String String Int | PersonNameZipAndEMail String String String Int String
getZipFromPerson :: Person -> Int
getZipFromPerson (PersonNameAndZip _ _ _ nZip) = nZip
getZipFromPerson (PersonNameZipAndEMail _ _ _ nZip _) = nZip
"A" 'a' 16802
secondFromList will execute with runtine error when there is less than two elements in the list.main :: IO ()
main =
do
print (secondFromList "H")
secondFromList :: [a] -> a
secondFromList (_:x:_) = x
Test3-exe.exe: app\Main.hs:7:1-26: Non-exhaustive patterns in function secondFromList
import Prelude hiding (length) main :: IO () main = do print (length s) -- "caller perspective" for first parameter of function length s :: String s = ('H':'e':['l', 'l', 'o']) ++ (' ':"World!") length :: [a] -> Integer length [] = 0 -- "inner function perspective" - selected when list is empty length (_:lrx) = 1 + (length lrx) -- "inner function perspective" - selected when at least one element -- using the rest (lrx) for recursive call of length (again "caller perspective")