F# passing an operator with arguments to a function

Posted by dan on Stack Overflow See other posts from Stack Overflow or by dan
Published on 2009-11-30T02:57:32Z Indexed on 2010/04/07 1:23 UTC
Read the original article Hit count: 389

Filed under:
|
|

Can you pass in an operation like "divide by 2" or "subtract 1" using just a partially applied operator, where "add 1" looks like this:

List.map ((+) 1) [1..5];;  //equals [2..6]
// instead of having to write: List.map (fun x-> x+1) [1..5]

What's happening is 1 is being applied to (+) as it's first argument, and the list item is being applied as the second argument. For addition and multiplication, this argument ordering doesn't matter.

Suppose I want to subtract 1 from every element (this will probably be a common beginners mistake):

List.map ((-) 1) [1..5];;  //equals [0 .. -4], the opposite of what we wanted

1 is applied to the (-) as its first argument, so instead of (list_item - 1), I get (1 - list_item). I can rewrite it as adding negative one instead of subtracting positive one:

List.map ((+) -1) [1..5];;
List.map (fun x -> x-1) [1..5];; // this works too

I'm looking for a more expressive way to write it, something like ((-) _ 1), where _ denotes a placeholder, like in the Arc language. This would cause 1 to be the second argument to -, so in List.map, it would evaluate to list_item - 1. So if you wanted to map divide by 2 to the list, you could write:

List.map ((/) _ 2) [2;4;6] //not real syntax, but would equal [1;2;3] 
List.map (fun x -> x/2) [2;4;6] //real syntax equivalent of the above

Can this be done or do I have to use (fun x -> x/2)? It seems that the closest we can get to the placeholder syntax is to use a lambda with a named argument.

© Stack Overflow or respective owner

Related posts about partial-application

Related posts about operators