Haskell application function function

Say I have a list of functions

functions = [f, g, h] 

each with type a -> a

I also have a list of values, like numbers, but everything should work here.

 vals = [1,2,3] 

I want to apply each function in functions to the corresponding value in vals

My first instinct is to use lambda and zipWith like:

 zipWith (\fv -> fv) functions vals 

But frankly, it looks ugly, and not what I expect in such a nice language like Haskell. A functional application function sounds like a solution. Does something like this exist? Am I missing something, and is there a much nicer solution to my problem? I actually wrote this construct for the Project Euler solution. It works, but I don't like it.

+7
haskell higher-order-functions
source share
3 answers
 zipWith ($) fv 

$ is a functional application. The fact that it has a particularly low priority sometimes throws people on a cycle.

+16
source share

Surprisingly,

 zipWith id functions vals 

will work too!

But really, zipWith ($) is the right way to write this.

+11
source share

Here is another option that might make you think a little.

 >>> import Control.Applicative >>> let functions = ZipList [(+1), (*2), (*10)] >>> let values = ZipList [1, 2, 3] >>> getZipList (functions <*> values) [2, 4, 30] 

A ZipList is just a wrapper around a list. Definition <*> for a ZipList says "zip a list of functions (left) with a list of arguments (right) by applying each function to the argument in turn."

This contradicts the definition of <*> for a regular list, which says: "Take every possible pair (function, argument) from these two lists and apply the function to the argument."

+3
source share

All Articles