As far as I understand this function does the same than this one
You are correct in that the two code snippets are evaluated the same.
Could someone please help me understand the syntax of the first function
As @JeffreyScofield seems to have answered this part very nicely, I'll focus on the second part.
if any the difference in terms of how both functions are evaluated
The tl;dr is there is no difference and the assembly produced is actually identical. We'll use a simple Fibonacci example to show the assembly emitted both using the match with
and function
notations.
let rec fib n = match n with
| 0 -> 0
| 1 -> 1
| i -> fib (i - 1) + fib (i - 2)
and
let rec fib = function
| 0 -> 0
| 1 -> 1
| i -> fib (i - 1) + fib (i - 2)
both produce
fib:
subq $24, %rsp
.L102:
cmpq $1, %rax
je .L100
cmpq $3, %rax
je .L101
movq %rax, 0(%rsp)
addq $-4, %rax
call fib
.L103:
movq %rax, 8(%rsp)
movq 0(%rsp), %rax
addq $-2, %rax
call fib
.L104:
movq 8(%rsp), %rbx
addq %rbx, %rax
decq %rax
addq $24, %rsp
ret
.L101:
movq $3, %rax
addq $24, %rsp
ret
.L100:
movq $1, %rax
addq $24, %rsp
ret
Note: I intentionally removed the .align
s and such.
To verify the claim that these produce the same assembly (and are thus evaluated the same), you can simply put each function in a file and then run
$ ocamlopt -S fib-with-match.ml
$ ocamlopt -S fib-with-function.ml
when you diff
the two, you should see it return with no difference:
$ diff fib-with-match.s fib-with-function.s
$
It's very common to have functions that only contain match
expressions in OCaml, so as @JeffreyScofield said, function
has an argument that can be used for pattern matching. Therefore, it's effectively syntactic sugar.
Source: