Can somebody tell me the difference between these two definitions ?
let f x y = x y;;
which yields val f : int -> int -> int = <fun>
and this definition
let f = fun x y -> x y;;
which also yields val f : int -> int -> int = <fun>
?
CodePudding user response:
There is no difference.
let f x y = x y
is syntactic sugar for
let f = fun x y -> x y
which is syntactic sugar for
let f = function x -> function y -> x y
It's all the same and you can do for example
let incr = f 1
with any of them.
CodePudding user response:
All functions in OCaml take a single argument, and return a single value.
Here's a function that demonstrates this.
fun x -> x 1
We can apply this function to a value.
(fun x -> x 1) 2
But this is inconvenient, so we bind a name to this function.
let inc = fun x -> x 1
Functions are values in OCaml, so a function can return a function.
let add = fun x -> fun y -> x y
We can now apply this:
(add 1) 1
Or because of how this is processed:
add 1 1
All of this is very inconvenient in practice, there is shorthand syntax so we can just write:
let add x y = x y
But consider again:
let add = fun x -> fun y -> x y
This if a function that takes an argument and spits out a function that takes an argument. What if we stop at providing that first argument? Well, then we get a function back that takes the second argument and produces a sum.
let inc = add 1
In this case, we've partially applied the add
function. This lets us take bits of code like:
let some_list = [2; 3; 4] in
List.map (fun x -> add 1 x) some_list
And express it as:
let some_list = [2; 3; 4] in
List.map (add 1) some_list