Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Learn You a Haskell explains zip4:

--ghci> zip4 [2,3,3] [2,2,2] [5,5,3] [2,2,2]  
--   [(2,2,5,2),(3,2,5,2),(3,2,3,2)] 

Please critique my implementation:

zip4 :: [a] -> [a] -> [a] -> [a] -> [(a,a,a,a)]
zip4 xs ys zs as = zip4' xs ys zs as 
                    where zip4' [] _ _ _ = []
                          zip4' _ [] _ _ = []
                          zip4' _ _ [] _ = []
                          zip4' _ _ _ [] = []
                          zip4' (b:bs) (c:cs) (d:ds) (e:es) = (b,c,d,e) : zip4' bs cs ds es

Tests:

*Main> zip4 [2,3,3] [2,2,2] [5,5,3] []
[]
*Main> zip4 [2,3,3] [2,2,2] [5,5,3] [1]
[(2,2,5,1)]
*Main> zip4 [2,3,3] [2,2,2] [5,5,3] [3]
[(2,2,5,3)]
*Main> zip4 [2,3,3] [2,2,2] [5,5,3] [3..100]
[(2,2,5,3),(3,2,5,4),(3,2,3,5)]
*Main> zip4 [1,1,1] [2,2,2] [3,3,3] (replicate 100 100)
[(1,2,3,100),(1,2,3,100),(1,2,3,100)]
share|improve this question

1 Answer 1

up vote 3 down vote accepted

The end-of-list patterns can be combined into one:

zip4 (b:bs) (c:cs) (d:ds) (e:es) = (b,c,d,e) : zip4' bs cs ds es
zip4 _ _ _ _ = []

There's no need for a separate zip4' helper.

This definition is correct, but it's unnecessarily complex. List functions like this are usually defined in terms of more general list functions like map, rather than by explicit recursion. The actual definition of zip4 is:

zip4 = zipWith4 (,,,)

Doing recursion exercises like reimplementing standard list functions can teach you the bad habit of using recursion even when you don't need it. Good Haskell code does almost all list manipulation with high-order functions or list comprehensions. It's better practice to use them than reimplement them.

share|improve this answer
    
In your defintiion of zip4, would zip4 [] [1] [2] [3] not hit the first pattern match then? I (evidently mistakenly) thought that (x:xs) pattern match would hit the empty list ([]). –  Kevin Meredith May 17 '14 at 14:59
1  
x:xs is a constructor pattern, so it only matches values of the : constructor, i.e. nonempty lists. –  Anonymous May 17 '14 at 15:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.