Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the purpose of the y parameter in this Haskell code

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading