AtilioA
AtilioA

Reputation: 440

Using map with function that has multiple arguments

Is it possible to use map with a function that takes multiple arguments?

I want to use map's second and third arguments repeatedly as the function's arguments. As in

mapF x y z = map (f y z) [1, 2, 3]

So it'll evaluate f with the same y and z values, but with x = 1, x = 2, x = 3 and so on.

Upvotes: 4

Views: 11826

Answers (2)

Bi Rico
Bi Rico

Reputation: 25823

You should use a lambda function, to see this works lets start by using a helper function to map f over some list.

map helper [1, 2, 3] where
  helper x = f x y z

In Haskell there are two syntax for functions so lets use the lambda syntax to define our helper function:

map helper [1, 2, 3] where
  helper = \x -> f x y z

using the lambda syntax we don't need to give our helper function an explicit name, it can just be an anonymous function we map over the input

map (\x -> f x y z) [1, 2, 3]

So now you can say

mapF y z = map (\x -> f x y z) [1,2,3]

But presumably you don't want x to be 1, 2 and 3, you want it to be a list you pass as an argument to mapF. So you need to give that a different name:

mapF xs y z = map (\x -> f x y z) xs

It is Haskell convention to use s as a suffix for variables that hold lists or other containers. So if one value is x then a list of them is xs

Upvotes: 8

Cliff Stamp
Cliff Stamp

Reputation: 571

There are guaranteed to be better ways to do this (still learning) but you can:

f' = map f [1,2,3]

f' is now a list of partially applied f

g y z= map (\h -> h y z) f'

will take each of those functions and run it on the arguments y z.

You can hack that all in one line.

Upvotes: 4

Related Questions