문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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. newtyped) as ZipLists, the semantics is "zippery" application - i.e. one-on-one, and pure x = ZipList $ repeat x.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top