Reputation: 7186
Part of some computation I am doing in Haskell results in a list of functions that map Float
to Float
. I'd like to apply a single argument to all these functions, like so:
-- x :: Float
-- functions :: [Float -> Float]
map (\f -> f x) functions
Is there a way to do this without making use of a throw-away lambda function? I've searched Hoogle for what I think the signature should be ([a -> b] -> a -> [b]
) with no luck.
Upvotes: 4
Views: 996
Reputation: 71119
functions <*> pure x
should do it. Import Control.Applicative
module first.
Also consider this:
Prelude Control.Applicative> [(1+),(2+)] <*> pure 4
[5,6]
Prelude Control.Applicative> [(1+),(2+)] <*> [4]
[5,6]
Prelude Control.Applicative> [(1+),(2+)] <*> [4,5]
[5,6,6,7]
Prelude Control.Applicative> [(+)] <*> [1,2] <*> [4,5]
[5,6,6,7]
Prelude Control.Applicative> (+) <$> [1,2] <*> [4,5]
[5,6,6,7]
Prelude Control.Applicative> getZipList $ ZipList [(1+),(2+)] <*> ZipList [4,5]
[5,7]
Prelude Control.Applicative> getZipList $ ZipList [(1+),(2+)] <*> pure 4
[5,6]
<$>
is just a synonym for fmap
. <*>
applies what's "carried" in the applicative functor on the left, to what's on the right, according to a certain semantics. For naked lists, the semantics is the same as list monad - make all possible combinations - apply each function from the left to each object on the right, and pure x = [x]
. For lists tagged (i.e. newtype
d) as ZipList
s, the semantics is "zippery" application - i.e. one-on-one, and pure x = ZipList $ repeat x
.
Upvotes: 6
Reputation: 68172
You can use the $
operator, which is just function application:
map ($ x) functions
(This presupposes that x
is in scope for the expression.)
Hoogle can only find functions, not arbitrary expressions. Since you're using map
, you wanted to search for a function like (a -> b) -> a -> b
rather than anything involving lists. Given a normal function, passing it to map
makes it act on lists.
Upvotes: 9