3
votes

I am a beginner in Haskell, and I have been told that I should avoid using head and tail for list operation and use pattern matching instead. I got a code snippet here, and I wonder how should this be converted so that no head or tail is used?

myzipWith :: (a->b->c) -> [a] -> [b] ->[c]
myzipWith func [] [] = []
myzipWith func listA listB =
    [func (head listA) (head listB) ] ++ (myzipWith func (tail listA) (tail listB))
2
Replace the final equation with myzipWith func (x:xs) (y:ys) = func x y : myzipWith func xs ys.Alexis King
There are good reasons to avoid head and tail. Let me ask, out of curiosity: were you given them?jub0bs
Knowing how head and tail are defined should help: head (x:_) = x and tail (_:xs) = xs.chepner
@chepner I know the definition but I was just not so familiar how to deal with the input parameter (sry idk whether I have used a right term) alongside with the function signature. Thanks anyway :)chungonion

2 Answers

7
votes
myzipWith :: (a->b->c) -> [a] -> [b] ->[c]
myzipWith func [] [] = []
myzipWith func (headA:restA) (headB:restB) =
    [func headA headB] ++ myzipWith func restA restB

But note the append (++) isn't necessary. This would be more idiomatic (and efficient):

    func headA headB : myzipWith func restA restB
4
votes
myzipWith func (a:as) (b:bs) = [func a b] ++ (myzipWith func as bs)

The syntax function (x:xs) splits the list passed to function into two parts: the first element x and the rest of the list xs.