list 列表构造/连接的语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5649435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:38:09  来源:igfitidea点击:

Syntax for list construction / concatenation

listhaskellsyntax

提问by Colin Woodbury

I've only been at Haskell for two days now, and was wondering what the difference between the two function definitions below are:

我现在只在 Haskell 呆了两天,想知道下面两个函数定义之间的区别是什么:

Prelude> let swap (x1:x2:xs) = x2:x1:xs
Prelude> swap [1..5]
[2,1,3,4,5]
Prelude> let swap' (x1:x2:xs) = [x2] ++ [x1] ++ xs
Prelude> swap' [1..5]
[2,1,3,4,5]

That is, what makes x2:x1:xs different from [x2] ++ [x1] ++ xs ? Please and thanks.

也就是说,是什么使 x2:x1:xs 与 [x2] ++ [x1] ++ xs 不同?请和谢谢。

回答by Jeff Foster

The type signatures are a good place to start:

类型签名是一个很好的起点:

(:) :: a -> [a] -> [a]
(++) :: [a] -> [a] -> [a]

You can find these out with :type (:)and :type (++)in ghci.

您可以找到这些出同:type (:):type (++)在ghci中。

As you can see from the type signatures, both are used to produce lists.

从类型签名中可以看出,两者都用于生成列表。

The :operator is used to construct lists (and to take them apart again for pattern matching). To make a list [1,2,3]you just build it up with 1 : 2 : 3 : []. The first element of :is the item to add on the front of the list, and the second element is either a list (also built up with :or the empty list signified by []).

:运算符用于构造列表(并再次将它们分开以进行模式匹配)。要制作一个列表,[1,2,3]您只需使用1 : 2 : 3 : []. 的第一个元素:是要添加到列表前面的项目,第二个元素是一个列表(也由 构建:或由 表示的空列表[])。

The ++operator is list concatenation. It takes two lists and appends them together. [1,2,3] ++ [4,5,6]is legal, whereas 1 ++ [1,2,3]is not.

++运营商连接列表。它需要两个列表并将它们附加在一起。 [1,2,3] ++ [4,5,6]是合法的,而1 ++ [1,2,3]不是。

回答by Ingo

This has nothing to do with syntax. (:) and (++) are just different operators. (:) is a constructor who constructs a list from an element and another list. (++) makes a new list that is the concatenation of two lists. Because (++) is not a constructor you can't use it in patterns.

这与语法无关。(:) 和 (++) 只是不同的运算符。(:) 是一个构造函数,它从一个元素和另一个列表构造一个列表。(++) 生成一个新列表,该列表是两个列表的串联。因为 (++) 不是构造函数,所以不能在模式中使用它。

Now we come to Syntax: the notation

现在我们来到语法:符号

[x2]

that you use is a shorthand for

你使用的是简写

x2:[]

So what you really have done in the second example is:

所以你在第二个例子中真正做的是:

(x2:[]) ++ (x1:[]) ++ xs

Therefore, when constructing a list, you can't avoid (:), it's ultimatively the only way to do it. Note that you must construct intermediate lists to be able to use (++).

因此,在构建列表时,您无法避免 (:),它最终是唯一的方法。请注意,您必须构造中间列表才能使用 (++)。