I need a Haskell function that takes a list of functions and a list of elements and applies the functions to the elements like this: the first function to the first element, the second function to the second element, etc. If any of the lists stop, I want the fuction to stop. The difinition I came up with is this:
apply :: [(a -> b)] -> [a] -> [b]
I would like it to work something like this:
apply [(+1), (*3), (^2)] [1,2,3] == [2,6,9]
apply [even, odd] [1..] == [False, False]
Things I tried so far:
apply :: [(a -> b)] -> [a] -> [b]
apply [] _ = []
apply (f:fs) x = (f x) : (apply fs x)
zipWith
is definitely a useful function to know about. As the above commenters say, bothzipWith ($)
andzipWith id
will do what you want. They're the same because($)
is actually the same asid
, just restricted to functions (that's a little mind blowing at first, but it's true and I would encourage you to work out why) - for this reason I prefer using($)
because it's more obvious you're talking about function application. – Robin Zigmond