(x:xs)模式Haskell逻辑

时间:2016-02-08 20:10:07

标签: haskell cons

让我们说有一个简单的功能:

maximum' :: (Ord a) => [a] -> a  
maximum' [] = error "maximum of empty list"  
maximum' [x] = x  
maximum' (x:xs) = max x (maximum' xs)

我理解这个想法和(x:xs)的作用。正如这里详细解释的那样 What do the parentheses signify in (x:xs) when pattern matching? 但有一件小事让我无法理解。由于 cons :运算符将x附加到列表xs,为什么x是函数参数列表的第一个元素,而xs是我们使用时的尾部(x:xs)??? ,好像(x:xs)在参数列表上调用head和tail。

2 个答案:

答案 0 :(得分:4)

这只是一般模式的一个实例,类型的构造函数既用于构造该类型的元素又用于解构。如果你写了

data MyList a = Empty | Cons a (MyList a)
你会写

maximum' :: (Ord a) => MyList a -> a  
maximum' Empty = error "maximum of empty list"  
maximum' (Cons x Empty) = x  
maximum' (Cons x xs) = max x (maximum' xs)

除了列表实际上等同于

data [a] = [] | a:as

所以,就像其他数据类型一样,:用于构造和解构非空列表。

答案 1 :(得分:3)

cons运算符不附加,它预先添加。即x : xs生成的列表包含x作为其第一个元素,xs作为其余元素。因此,模式x : xs同样匹配列表,其中x作为第一个元素,xs作为其余元素。

相关问题