6

How can I create a partial function application for a non-symmetric operator such as the modulus operator with regards to the first argument without any argument names in F#? My first attempt was

let mod10 = (%) 10 which of course translates to

mod10(x) = 10 mod x instead of the desired

mod10(x) = x mod 10. Certainly I could write

let mod10 x = (%)x 10 but I'd like to not have to name the argument so is there some placeholder that can be used, something like

let mod10 = (%)_ 10?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
Christian
  • 7,433
  • 4
  • 36
  • 61

2 Answers2

20

Here's solution based on functional composition.

let mod10 = (%) >> (|>) 10

UPD Here was a wordy explanation, but programmers speak the code, so I guess the following will describe it much better, in a manner of mathematical proof.

The following expressions are equal:

let m1 x = x % 10                    
let m2 x = (%) x 10                  // x (op) y = (op) x y
let m3 x = ((%) x) 10                // f x y = (f x) y
let m4 x = 10 |>         ((%) x)     // f x = x |> f
let m5 x = ((|>) 10)     ((%) x)     // x |> f = (|>) x f
let m6 x = ((%) x)    |> ((|>) 10)   // f x = x |> f
let m7 x = (x |> (%)) |> ((|>) 10)   // (op) x = x |> (op)
let m8 x = x |> ((%)  >> ((|>) 10))  // f(x) |> g = x |> (f >> g)
let m9   =       (%)  >> ((|>) 10)   // remove formal argument
let m10  =       (%)  >>  (|>) 10    // remove unnecessary parenthesis

Alternative syntax:

let mod10_2 = (|>) 10 << (%)
Be Brave Be Like Ukraine
  • 7,596
  • 3
  • 42
  • 66
13

You can define flip function which is common in point-free style:

let inline flip f x y = f y x

and use it like this:

let (%-) = flip (%)
let mod10 = (%-) 10

or directly like this:

let mod10 = flip (%) 10

Point-free style is not always readable (as in this example) and not popular in F# programming.

pad
  • 41,040
  • 7
  • 92
  • 166
  • Ah nice 'trick'! I agree that point-free style isn't always readable but I guess that goes for all styles. – Christian Jul 07 '12 at 21:00
  • 1
    Programming isn't really a popularity contest. Besides, it's hard to make a call on popularity. It might be _uncommon_ but that doesn't mean it's unpopular. I like point-free in many cases, but in others it does reduce readability. – OJ. Jul 09 '12 at 09:33
  • @pad: Our programming lives are full of subjectivity aren't they? :) That's what makes the world colourful! – OJ. Jul 14 '12 at 22:45