Reputation: 41939
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 S-Z'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]
Upvotes: 2
Views: 568
Reputation: 74244
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.
Upvotes: 5
Reputation: 34398
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]
Upvotes: 8