Home > Mobile >  What is the purpose of the y parameter in this Haskell code
What is the purpose of the y parameter in this Haskell code

Time:06-19

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 ?

I'd really appreciate it if someone could explain the logic for me.

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