devoured elysium
devoured elysium

Reputation: 105037

Trying to apply map to "inner" arguments of functions in Haskell

Let's define an arbitrary function

someFunc a b = ...

if I ever need it, I know I can do something like

map (someFunc a) [b0, b1, b2, ..., bn]

and I'll get as result

[(someFunc a b0), (someFunc a b1), ..., (someFunc a bn)]

There is nothing new here. But what if instead of using the map's 2nd argument to vary b, I wanted to vary a (a "inner" argument)?

map (someFunc ? b) [?0, ?1, ?2, ..., ?n]

Is there any way to accomplish this in Haskell? If not, what would be the work around for this?

I know I probably wasn't very clear about what I'm posting about. If needed, I can try to reformulate my question :(

Upvotes: 3

Views: 354

Answers (2)

Paul Johnson
Paul Johnson

Reputation: 17786

You could use

flip :: (a -> b -> c) -> b -> a -> c

So you would say

map (flip someFunc b) [a1...]

For more complicated cases with more arguments you would have to use a lambda. In theory you can always do it with the right combination of flips and arguments, but the lambda version will probably be more readable.

Upvotes: 4

sepp2k
sepp2k

Reputation: 370082

You can either use a lambda

map (\a -> someFunc a b) ...

or the higher order functionflip, which returns the given function with its arguments flipped around:

map (flip someFunc b) ...

Upvotes: 11

Related Questions