简体   繁体   English

Haskell ::递归中使用括号

[英]Haskell :: The Use of Brackets in Recursion

I'm just wondering, for recursion example: 我只是想知道,对于递归示例:

squaresRec :: [Double] -> [Double]   
squaresRec [] = []                       
squaresRec (x:xs) = x*x : squaresRec xs

Why on the recursive case, there is no bracket? 为什么在递归的情况下,没有括号? Shouldn't it suppose to be like this: 它不应该像这样:

squaresRec :: [Double] -> [Double]   
squaresRec [] = []                       
squaresRec [x:xs] = x*x : squaresRec xs

I know this will not work. 我知道这行不通。 But just wondering the explanation behind it. 但只是想知道其背后的解释。

[] matches the empty list. []匹配空列表。

[1] matches a list containing exactly one element, and that must be a number equal to one. [1]匹配仅包含一个元素的列表,该列表必须是等于1的数字。 Note that [1] is actually syntactic sugar for (1:[]) , ie what this really matches is: a list beginning with the number 1 , followed by a list that is empty... which is just a complicated way of saying “a list containing the single element 1 ”. 请注意, [1]实际上是(1:[])语法糖,也就是说,它真正匹配的是:一个以数字1开头的列表,然后是一个空列表...这只是一种复杂的说法“包含单个元素1的列表”。

(x:xs) matches a list that begins with x , followed by xs (and that may contain any number of elements, possibly zero). (x:xs)匹配以x开头,后跟xs (并且可以包含任意数量的元素,可能为零)的列表。 Ie this pattern matches any list with at least one element. 即,该模式匹配具有至少一个元素的任何列表。

[x:xs] matches again a list which contains exactly one element, and that element should match the pattern (x:xs) . [x:xs]再次匹配包含恰好一个要素的列表,并且该元素应该匹配图案(x:xs) (Which doesn't make sense even type-wise, because your lists contain Double -numbers, not lists.) (哪怕类型也不有意义,因为您的列表包含Double精度数字,而不是列表。)

I had the same problem because I'm coming from Erlang. 我有同样的问题,因为我来自Erlang。

The thing to understand is that the [head|tail] pattern we have in Erlang is actually translated by the cons function in Haskell, which is the : operator. 要了解的是,实际上我们在Erlang中使用的[head | tail]模式是由Haskell中的cons函数(即:运算符)转换的。 The parenthesis are just here to isolate the function parameters, like (3+4) would do. 括号只是用来隔离功能参数,就像(3 + 4)一样。

I know it's tempting to ask "why though???" 我知道问“为什么会这样???”很诱人。 and that it visually makes more sense, but : is how we build (and separate when pattern-matching) the head and the tail of a linked list. 并且从视觉上讲更有意义,但是:是我们如何构建(和模式匹配时分开)链接列表的开头和结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM