(x:xs)模式Haskell逻辑 [英] (x:xs) pattern Haskell logic
问题描述
maximum'::(Ord a)=> [a] - >
maximum'(x:xs)= max x(maximum'xs)$ b $'b $ b maximum'[] = error b
我理解这个想法和什么(x:xs)。正如它在这里详细解释
什么当模式匹配?
时,圆括号表示(x:xs)吗?但是有一件事情我无法摆脱我的头脑。由于 cons :运算符将x附加到列表xs中,为什么x是函数参数列表的第一个元素,而xs是我们使用的尾部(x:xs)? 就像if(x:xs)在参数列表上调用头部和尾部一样。
这只是一般模式的一个实例,一个类型的构造函数同时用于构造该类型的元素,解构。如果你写了
data MyList a = Empty |你可以写一个(MyList a)
maximum'::(Ord a)=> MyList a - > (空x)=最大x(最大'xs)$ b最大'空'=错误'最大空列表'
最大'(缺x空)= x
最大' $ b
除了列表实际上等同于
data [a] = [] | a:as
就像其他数据类型一样,: code>用于构造和解构非空列表。
Let's say there is a simple function:
maximum' :: (Ord a) => [a] -> a
maximum' [] = error "maximum of empty list"
maximum' [x] = x
maximum' (x:xs) = max x (maximum' xs)
I understand the idea and what (x:xs) does. As it was explained in details here What do the parentheses signify in (x:xs) when pattern matching? but there is one little thing that I cannot get out of my head. Since cons: operator appends x to a list xs, why is it that x is the first element of function argument list and xs is the tail when we use (x:xs)??? as if (x:xs) calls head and tail on argument list.
This is just an instance of the general pattern that the constructor for a type is both used to construct elements of that type and to deconstruct. If you wrote
data MyList a = Empty | Cons a (MyList a)
you'd write
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)
Except that lists are actually defined equivalently to
data [a] = [] | a:as
so, just as with other data types, :
is used both to construct and to deconstruct nonempty lists.
这篇关于(x:xs)模式Haskell逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!