Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does xs in this function work?

Tags:

haskell

I am reading Hutton's book, Programming in Haskell. Here is a function:

pairs :: [a] -> [(a,a)]

pairs xs = zip xs (tail xs)

e.g.

>pairs [1,2,3,4]

>[(1,2),(2,3),(3,4)] --result

Problem is how to read this function ? from left to right?

I am confused how "tail" leave 1 element and then combine it with next element using "zip" Since "tail" suppose to get all remaining elements from the list right?

like image 499
CodeFarmer Avatar asked Jan 20 '26 18:01

CodeFarmer


1 Answers

I haven't read the book you mentioned, but I'll try to explain what I know.

You're right about the tail function returning everything except the first element of the list. Let's see how zip works,

zip [1, 2, 3, 4] [5, 6, 7, 8]

gives,

[(1, 5), (2, 6), (3, 7), (4, 8)]

Now, consider the output we need from the input we have, observe the transformation required from input to output,

[1, 2, 3, 4] -> [(1,2),(2,3),(3,4)]

From the above application of zip, we can see the output we need can be obtained by calling zip with,

zip [1, 2, 3] [2, 3, 4]

Now, from the docs on zip function, we can see that if the two given lists are of unequal length, the extra items in the longer list are discarded. So, we'd get the same result with,

zip [1, 2, 3, 4] [2, 3, 4]

in which the last 4 in the first input list would be discarded and we get the result we want.

This can be written in a function as,

pairs xs = zip xs (tail xs)

If it is something else you are confused about, do let me know.

like image 151
sharat87 Avatar answered Jan 23 '26 08:01

sharat87



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!