Search code examples
ocamlsubtractionpartial-application

cleanest partial application of subtraction operator


If I want a function that subtracts an int argument from the number 2, I can do

let two_minus = (-) 2

But what if I want a function that subtracts 2 from an int argument?

In Haskell, I can do

let minus2 = flip (-) 2

But in Ocaml 4.02, flip is not part of the standard library.

For now, I've settled on

let minus2 = (+) ~-2

which adds negative 2 to an int argument. I find it looks cleaner than

let minus2 = fun x -> x-2

... or at least it takes less characters.

Is there a better, more idiomatic way?


Solution

  • In Haskell, you can do what you want with operator sections, which is much cleaner than flip imo:

    Prelude> :t (2 -)
    (2 -) :: Num a => a -> a
    Prelude> :t ((-) 2)
    ((-) 2) :: Num a => a -> a
    

    OCaml does not support this nicety (afaik). However, if you like flip, it is trivial to define your own:

    let flip f x y = f y x;;
    

    Or you can use a standard library that has it defined already, like Core and Batteries. E.g.,

    # open Core 
    utop # Fn.flip;;
    - : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c = <fun>
    

    fwiw, in the absence of operator sections, I find fun x -> x-2 much clearer than either of the two alternatives you propose. It may not look as nice, but it is immediately clear what it means.

    Favoring clear and very explicit expressions over clever and concise ones is very idiomatic OCaml.