I am trying to learn Haskell from Haskell Road to Logic
and came across this example:
mnmInt :: [Int] -> Int
mnmInt [] = error "empty list"·
mnmInt [x] = x
mnmInt (x:xs) = min x (mnmInt xs)
I understand the functions takes a list of Int –
Checks if empty
if not
checks if it’s a list with 1 int if so return x
if not
plug mnmInt with xs parameter to min.
how does it reach the base case? what does the xs stand for?
min implementation:
min' :: Int -> Int -> Int
min' x y | x <= y = x
| otherwise = y
doesn’t take an array.
(x:xs)is pattern matching syntax. Pattern matching lets you “destructure” data types and bind them to names. In this case x is the head of the list, and xs is the tail.min'doesn’t need to take a list because x is the head of the list, not a list itself.min'itself finds the minimum value between twoInts,mnmIntwill eventually expand out to something like(min' 1 (min' 2 (min' 3 4)))if you pass in a list that looks like[1,2,3,4].This is easy to see if you evaluate the code by hand, which I highly suggest you try. Remember,
(x:xs)is two names, which are the head and tail of the list. You might want to play around with constructing lists using:Here is an example that shows how pattern matching relates to code flow.
if you call
foo [1,2]it will output “two”, if you dofoo [1,2,3]it will give you “some other value”, and if you dofoo []it will return"none"