Zipping two lists in Haskell

Studying a pure functional programming, such as Haskell, can be an eye-opening experience. The standard library in Haskell provides a zip function, which combines the elements of two lists into a single list of tuples. I decided to implement my own version, named zip prime (actually, zip’ since Haskell allows a function name to include the prime (symbol). The simplicity of this code amazes me:


The first line is the function declaration.  It states that zip’ takes two lists of possibly different element types (types a and b) and returns a list of tuples of those element types.

The next line explains what should happen when the second list is empty; return an empty list. Similarly, the line after that explains that an empty list should be returned if the first list is empty.

The fourth and last line of that function covers the case when neither list is empty. It creates a tuple from the first element in each list. That tuple then becomes the list element which precedes the result of zipping together what’s left of the two lists (i.e. zipping their tails).

What could be simpler?! I wish that Swift had this kind of  powerful pattern matching at the function definition level.

About Josh Smith

Josh Smith is a musician at heart, and a software developer by obsession. He lives in Arizona, plays classical music on the piano, jazz on the guitar, and enjoys brutally long rides on his bicycle. He has a wonderful wife and thinks that, in general, life is good.
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.