Jono
Jono

Reputation: 2054

F# treating operators as functions

In F#, is there a way to treat an operator as a function? In context, I'd like to partially apply operators (both infix and prefix), but the compiler only seems happy to partially apply functions.

Example: Instead of being able to write List.map (2 **) [0..7];; I have to define my own function pow x y (and then another function let swap f x y = f y x;; because the compiler won't let me partially apply |> either, as in List.map (|> pow 2) [0..7];;.) In the end, my code needs to be List.map (swap pow 2) [0..7];; to work.

Upvotes: 3

Views: 346

Answers (2)

Brian
Brian

Reputation: 118865

There are no 'operator sections' a la Haskell; use a lambda to partially apply operators, e.g.

(fun x -> x - 10)

You can partially apply the first argument if you make an infix operator be prefix by surrounding it in parens, e.g.

(fun x -> 10.0 / x)

and

((/) 10.0)

mean the same thing.

Upvotes: 3

Daniel
Daniel

Reputation: 47904

I would just do:

[0..7] |> List.map (fun n -> pown n 2)

Or, if 2 is the base:

[0..7] |> List.map (pown 2)

This works too:

[0.0..7.0] |> List.map (( ** ) 2.0)

Upvotes: 5

Related Questions