Oleg
Oleg

Reputation: 1559

Order of Evaluation of Arguments in Ocaml

I would like to know why does ocaml evaluate the calls from right to left, is that a FP principle or it doesn't matter at all to a FP language ?

A quicksort example :

let rec qs = function
    | [] -> []
    | h::t -> let l, r = List.partition ((>) h) t in
    List.iter (fun e -> print_int e; print_char ' ') l; Printf.printf " <<%d>> " h;
    List.iter (fun e -> print_int e; print_char ' ') r; print_char '\n';
    (qs l)@(h::qs r)

In my example the call to (qs r) is evaluated first and then (qs l) but I expected it to be otherwise.

# qs [5;43;1;10;2];;
1 2  <<5>> 43 10 
10   <<43>> 
     <<10>> 
     <<1>> 2 
     <<2>> 
- : int list = [1; 2; 5; 10; 43]

EDIT :

from https://caml.inria.fr/pub/docs/oreilly-book/html/book-ora029.html

In Objective CAML, the order of evaluation of arguments is not specified. As it happens, today all implementations of Objective CAML evaluate arguments from left to right. All the same, making use of this implementation feature could turn out to be dangerous if future versions of the language modify the implementation.

Upvotes: 3

Views: 2838

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

The order of evaluation of arguments to a function is not specified in OCaml.

This is documented in Section 6.7 of the manual.

In essence this gives the greatest possible freedom to the system (compiler or interpreter) to evaluate expressions in an order that is advantageous in some way. It means you (as an OCaml programmer) must write code that doesn't depend on the order of evaluation.

If your code is purely functional, its behavior can't depend on the order. So you need to be careful only when writing code with effects.

Update

If you care about order, use let:

let a = <expr1> in
let b = <expr2> in
f a b

Or, more generally:

let f = <expr0> in
let a = <expr1> in
let b = <expr2> in
f a b

Update 2

For what it's worth, the book you cite above was published in 2002. A lot has changed since then, including the name of the language. A more current resource is Real World OCaml.

Upvotes: 7

Related Questions