简体   繁体   中英

Mapping `apply` to List of Functions

Learn You a Haskell demonstrates mapping with currying:

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

xs now equals [(1*), (2*), (3*)]

EDITED to correct order per Antal SZ 's comment.

We can get the first item in the list, and apply 3 to it - returning 3*1.

*Main> (xs !! 0) 3
3

But, how can I apply the below foo to apply 1 to all curried functions in xs ?

*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 ?

import Control.Applicative

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

The <$> function is the same as fmap in infix form. 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. It takes a normal value and returns an 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 . 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.

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

map (\x -> x foo) xs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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