(x:xs) 模式 Haskell 逻辑

(x:xs) pattern Haskell logic

假设有一个简单的函数:

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) 在参数列表上调用 head 和 tail 一样。

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

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

因此,与其他数据类型一样,: 用于构造和解构非空列表。

cons 运算符不是追加,而是前置。即 x : xs 生成一个列表,其中包含 x 作为其第一个元素, xs 作为其余元素。因此,模式 x : xs 同样匹配一个列表,其中 x 作为第一个元素, xs 作为其余元素。