Home > Back-end >  What is the purpose of the y parameter in this code?
What is the purpose of the y parameter in this code?

Time:07-05

This Haskell code prints out [0,10,20,30,40,50] but I don't understand what the y is suppose to do in the third line.

f [] = []
f [x] = [x]
f (x:y:xs) = x : f xs
main = print (f [0,5..50])

Why doesn't it print the same result if I say f (x:xs) = x : f xs instead?

CodePudding user response:

(x:y:xy) is matching a list with at least two elements and binding x to the first element, y to the second and xs to the tail of the list.

By calling x: f xs the second element is removed from the resulting list.

As this value is never used, it doesn't need to be called y at all.

f [] = []
f [x] = [x]
f (x:_:xs) = x : f xs

main = print (f [0,5..50])

If you had instead written:

f [] = []
f [x] = [x]
f (x:xs) = x : f xs

main = print (f [0,5..50])

The result would just be the original list, as that second element is never "dropped."

CodePudding user response:

The pattern in f (x:y:xs) is saying: get the input to the function, assign the first element of the list to x, the second to y and the rest (tail) of the list to xs. And this function is returning the first element x followed by the result of applying f to xs. In essence, you are removing every second element from the list.

  • Related