0

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.

4

2 回答 2

5

(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 two Ints, mnmInt will 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.

foo (x:y:[]) = "two"
foo ([]) = "none"
foo (_) = "some other value"

if you call foo [1,2] it will output "two", if you do foo [1,2,3] it will give you "some other value", and if you do foo [] it will return "none"

于 2012-05-15T22:27:53.523 回答
1

You can write a list in two ways in Haskell, first like [1,2,3,4,5], which is only syntactic sugar for 1:2:3:4:5:[]. Now the pattern (x:xs) matches with a list like this:

    head(x:xs) = x
    --> head [1,2,3,4,5] = head 1:2:3:4:5:[] = head 1:xs = 1

i hope this example make it clear to you how a list pattern works.

于 2012-05-16T10:03:07.657 回答