Haskell(:)和(++)的区别 [英] Haskell (:) and (++) differences
问题描述
对于这样的问题,我感到抱歉.我不太清楚Haskell中:
和++
运算符的区别.
I'm sorry for a question like this. I'm not too sure about the difference of the :
and ++
operator in Haskell.
x:y:[] = [x,y]
还
[x] ++ [y] = [x,y]
至于反向功能对我来说是一个问题,
as for the reverse function which arose this question for me,
reverse ::[a]->[a]
reverse [] = []
reverse (x:xs) = reverse(xs)++[x]
为什么以下各项不起作用?
Why doesn't the following work?
reversex ::[Int]->[Int]
reversex [] = []
reversex (x:xs) = reversex(xs):x:[]
出现类型错误.
推荐答案
:
运算符称为"cons"运算符,用于将head元素添加到列表的前面.因此,[]
是一个列表,而x:[]
在x
之前是空白列表,从而形成了列表[x]
.如果然后使用y:[x]
弊端,则会得到与y:x:[]
相同的列表[y, x]
.
The :
operator is known as the "cons" operator and is used to prepend a head element to a list. So []
is a list and x:[]
is prepending x
to the empty list making a the list [x]
. If you then cons y:[x]
you end up with the list [y, x]
which is the same as y:x:[]
.
++
运算符是列表串联运算符,它将两个列表作为操作数并将它们组合"为一个列表.因此,如果您有列表[x]
和列表[y]
,则可以将它们连接起来:[x]++[y]
以获得[x, y
].
The ++
operator is the list concatenation operator which takes two lists as operands and "combine" them into a single list. So if you have the list [x]
and the list [y]
then you can concatenate them like this: [x]++[y]
to get [x, y
].
请注意,:
包含一个元素和一个列表,而++
包含两个列表.
Notice that :
takes an element and a list while ++
takes two lists.
对于无效的代码.
reversex ::[Int]->[Int]
reversex [] = []
reversex (x:xs) = reversex(xs):x:[]
reverse函数将得出一个列表.由于:
运算符不将列表作为其第一个参数,因此reverse(xs):x
无效.但是reverse(xs)++[x]
是有效的.
The reverse function evaluates to a list. Since the :
operator does not take a list as its first argument then reverse(xs):x
is invalid. But reverse(xs)++[x]
is valid.
这篇关于Haskell(:)和(++)的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!