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
OCaml's function-application syntax, combined with the left-associativity of function application, makes this transparent.
The |> operator represents reverse function application.
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.
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)
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 *)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With