Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference of the function keyword and match with in OCaml

Tags:

syntax

ocaml

I'm currently learning OCaml today I came up to this piece of code.

let rec tree_to_list acc = function
  | Leaf x -> x::acc
  | Node (t1,t2) -> tree_to_list (tree_to_list acc t2) t1

As far as I understand this function does the same than this one

let rec tree_to_list2 acc t = match t with
  | Leaf x -> x::acc
  | Node (t1, t2) -> tree_to_list t1 (tree_to_list2 acc t2)

However, I do not understand the syntax behind the first function. I find the keyword function confusing. It is supposed to take one argument only such as :

function x -> x + 2

Could someone please help me understand the syntax of the first function and if any the difference in terms of how both functions are evaluated. Thanks in advance.

like image 897
Colin G.D. Avatar asked Oct 21 '15 17:10

Colin G.D.


1 Answers

Functions in OCaml are defined by giving patterns for the arguments. The common case of a simple variable name (like acc in your first function) is just a particular kind of pattern that matches all values.

So, one way to look at it is that fun defines a function with any number of arguments that can each be given by one pattern. On the other hand, function defines a function with one argument that can be given by any number of patterns.

# let dot = fun (a, b) (c, d) -> a *. c +. b *. d
val dot : float * float -> float * float -> float = <fun>

# let geti = function None -> 0 | Some i -> i;;
val geti : int option -> int = <fun>

The fun form can, in essence, be absorbed into the left hand side of a let to give a more concise notation.

That is,

let f = fun p1 p2 -> ...

can be written as

let f p1 p2 = ...

So for example:

let dot (a, b) (c, d) = a *. c +. b *. d

Your first function is using a combination of the two (a concise fun and a function on the right).

like image 154
Jeffrey Scofield Avatar answered Oct 18 '22 17:10

Jeffrey Scofield