Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change application order in OCaml

Tags:

ocaml

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

let a x = x * 4;;
let b y = y + 2;;

let c = a ??? b 3;;

print_int c;;

Should print 20

like image 785
Ramesh Avatar asked Nov 22 '10 04:11

Ramesh


People also ask

Is OCaml left or right associative?

OCaml's function-application syntax, combined with the left-associativity of function application, makes this transparent.

What does |> do in OCaml?

The |> operator represents reverse function application.

What does :: mean in OCaml?

Regarding the :: symbol - as already mentioned, it is used to create lists from a single element and a list ( 1::[2;3] creates a list [1;2;3] ). It is however worth noting that the symbol can be used in two different ways and it is also interpreted in two different ways by the compiler.


2 Answers

Sure, you can define it yourself:

let (@@@) f x = f x

Then, a @@@ b 3 evaluates to 20. Make sure to select a starting symbol such that it is right-associative (see here) ($... is left-associative)

like image 179
newacct Avatar answered Sep 23 '22 12:09

newacct


You just have to define a symbol for such applications:

let (@@@) f x = f x ;;

And then

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

does print 20.

Note that the next version of OCaml (3.13 or 4.00) will provide builtin primitives for applications that avoid creating intermediate partially applied functions:

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

The last one is the opposite of %apply:

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

Note that you cannot use ($) as it is left-associative in the definition of the OCaml parser:

let ($) f x = f x ;;
let a = f $ g 3;;  (* ok ! ??? *)
let a = f $ g $ g 3;; (* ERROR -> g is not an integer,
                        because OCaml computes (f $ g) first *)
like image 37
Fabrice Le Fessant Avatar answered Sep 26 '22 12:09

Fabrice Le Fessant