Reordering Orders in OCaml

Is there a way to change the order from left-associative to right-associative, except for parentheses? For example, in Haskell, you can write foo $ bar b , and foo will be applied to the result from bar b .

 let ax = x * 4;; let by = y + 2;; let c = a ??? b 3;; print_int c;; 

Gotta print 20

+7
ocaml
source share
2 answers

Of course, you can define it yourself:

 let (@@@) fx = fx 

Then a @@@ b 3 is evaluated to 20. Do not forget to select the start character so that it is correctly associative ( see here ) ( $... left-associative)

+6
source share

You just need to define a symbol for such applications:

 let (@@@) fx = fx ;; 

And then

 let fx = x * 4;; let gy = y + 2;; let a = f @@@ g 3;; print_int a;; 

outputs 20.

Please note that the next version of OCaml (3.13 or 4.00) will provide built-in primitives for applications that do not allow the creation of intermediate partially applied functions:

 external (@@@) : ('a -> 'b) -> 'a -> 'b = "%apply" external (|>) : 'a -> ('a -> 'b) -> 'b = "%revapply" 

The latter is the opposite of %apply :

 print_int (3 |> g |> f);; 

Note that you cannot use ($) since it is left-associative in the OCaml analyzer definition:

 let ($) fx = fx ;; let a = f $ g 3;; (* ok ! ??? *) let a = f $ g $ g 3;; (* ERROR -> g is not an integer, because OCaml computes (f $ g) first *) 
+4
source share

All Articles