Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaration order in let-bindings, Haskell vs OCaml

Tags:

haskell

ocaml

In Haskell, declaration order in let/where constructs does not matter, for example:

f x = let g1 x y = if x>y then show x else g2 y x
          g2 p q = g1 q p
      in ...

where g2 used in g1 before its declaration. But this is not a case in Ocaml:

# let a = b in
  let b = 5 in
  a;;
Warning 26: unused variable b.
Error: Unbound value b

Is there a reason why OCaml doesn't behave like Haskell? In the absence of forward declaration, this feature seems useful to me.

Is it because of strict evaluation in OCaml but lazy in Haskell?

like image 273
user1083265 Avatar asked Dec 06 '11 10:12

user1083265


2 Answers

OCaml uses "let rec" to indicate when the binding in a group can refer to each other. Without the extra "rec" the binding must be in top-down order. See "local definitions" at http://caml.inria.fr/pub/docs/manual-ocaml/expr.html for details.

like image 138
Chris Kuklewicz Avatar answered Oct 19 '22 01:10

Chris Kuklewicz


Not the strictness as such, but that's a symptom of the same problem.

Ocaml is not purely functional, which is to say that arbitrary function calls can do arbitrary I/O. This requires them to run in a predictable order, which requires both strictness and the let-ordering you've noticed.

like image 7
Baughn Avatar answered Oct 19 '22 00:10

Baughn