2

Suppose I have a list [0,1,2,3] and I want a new list with elements [(0,1), (1,2), (2,3)]. Is there a function to do this in Haskell?

Sam
  • 41
  • 6
  • I don't think there's any such function provided in the standard libraries - but it's easy to implement yourself. Hint: you'll need to use `zip`. – Robin Zigmond Feb 22 '20 at 16:31
  • @RobinZigmond Brilliant! Thanks!! I figured it out. I could just drop the first element of the list and zip it with its original self. – Sam Feb 22 '20 at 16:36

1 Answers1

6

You can make it work with zip where you pass it both the list, and the tail of that list. For example with pattern matching:

f :: [a] -> [(a, a)]
f [] = []
f xa@(_:xs) = zip xa xs

or with tail :: [a] -> [a]:

f :: [a] -> [(a, a)]
f xs = zip xs (tail xs)

the above will work, even for empty lists, since the zip will first pattern match on the first list, if that list is exhausted, it will not look at the second list.

Or in applicative style:

f :: [a] -> [(a, a)]
f = zip <*> tail
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555