Haskell: mapping function application

自闭症网瘾萝莉.ら 提交于 2019-12-10 10:15:22

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/13134857/haskell-mapping-function-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!