简体   繁体   中英

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. 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 ”.

(x:xs) matches a list that begins with x , followed by xs (and that may contain any number of elements, possibly zero). 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) . (Which doesn't make sense even type-wise, because your lists contain Double -numbers, not lists.)

I had the same problem because I'm coming from 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. The parenthesis are just here to isolate the function parameters, like (3+4) would do.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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