2
\$\begingroup\$

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)]
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ 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 ([]). \$\endgroup\$ Commented May 17, 2014 at 14:59
  • 1
    \$\begingroup\$ x:xs is a constructor pattern, so it only matches values of the : constructor, i.e. nonempty lists. \$\endgroup\$
    – Anonymous
    Commented May 17, 2014 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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