3

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.

AtilioA
  • 419
  • 2
  • 6
  • 19

2 Answers2

8

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

Paul Johnson
  • 17,438
  • 3
  • 42
  • 59
Bi Rico
  • 25,283
  • 3
  • 52
  • 75
3

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.

David Young
  • 10,713
  • 2
  • 33
  • 47
Cliff Stamp
  • 531
  • 5
  • 11
  • I don't get it. f won't work with only one argument. – AtilioA Jun 28 '18 at 02:09
  • 3
    Haskell is perfectly fine with only partially applying a function, it just makes a function which needs more arguments. For example if you say f = (2+) that makes a function which needs another argument so f 6 = 8, f 10 = 12 etc. . – Cliff Stamp Jun 28 '18 at 02:22
  • I'm confirming that this works, though I think Bi Rico's answer is more simple and intuitive. – AtilioA Jun 28 '18 at 11:50