简体   繁体   English

将`apply`映射到函数列表

[英]Mapping `apply` to List of Functions

Learn You a Haskell demonstrates mapping with currying: 了解一个Haskell演示了currying的映射:

*Main> let xs = map (*) [1..3]

xs now equals [(1*), (2*), (3*)] xs现在等于[(1 *),(2 *),(3 *)]

EDITED to correct order per Antal SZ 's comment. 按照Antal SZ的评论编辑纠正订单。

We can get the first item in the list, and apply 3 to it - returning 3*1. 我们可以获得列表中的第一项,并应用3 - 返回3 * 1。

*Main> (xs !! 0) 3
3

But, how can I apply the below foo to apply 1 to all curried functions in xs ? 但是,如何应用下面的foo1应用于xs所有curried函数?

*Main> let foo = 1
*Main> map foo xs

<interactive>:160:5:
    Couldn't match expected type `(Integer -> Integer) -> b0'
                with actual type `Integer'
    In the first argument of `map', namely `foo'
    In the expression: map foo xs
    In an equation for `it': it = map foo xs

Desired output: 期望的输出:

[1, 2, 3]

Use the ($) function... 使用($)函数...

Prelude> :t ($)
($) :: (a -> b) -> a -> b

...passing just the second argument to it. ......只传递第二个参数。

Prelude> let foo = 2
Prelude> map ($ foo) [(1*), (2*), (3*)]
[2,4,6]

Have you tried using applicative functors ? 你尝试过使用applicative functor吗?

import Control.Applicative

main = (*) <$> [1,2,3] <*> pure 1

The <$> function is the same as fmap in infix form. <$>函数与中缀形式的fmap相同。 It has the type signature: 它有类型签名:

(<$>) :: Functor f => (a -> b) -> f a -> f b

The <*> function is the functor equivalent of $ (function application): <*>函数是$ (函数应用程序)的仿函数:

(<*>) :: Applicative f => f (a -> b) -> f a -> f b

The pure function is similar to return for monads. pure函数类似于monad的return It takes a normal value and returns an applicative functor: 它需要一个正常值并返回一个applicative functor:

pure :: Applicative f => a -> f a

Hence the expression (*) <$> [1,2,3] <*> pure 1 is similar to applying the (*) function to all the values of [1,2,3] and pure 1 . 因此,表达式(*) <$> [1,2,3] <*> pure 1类似于将(*)函数应用于[1,2,3]pure 1所有值。 Since pure 1 only has one value it is equivalent to multiplying every item of the list with 1 to produce a new list of products. 由于pure 1仅有一个值,因此相当于将列表中的每个项目乘以1以生成新的产品列表。

或者您可以使用匿名函数:

map (\x -> x foo) xs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM