rec24 - CS 3110 Recitation 24 Streams and lazy evaluation...

This preview shows pages 1–2. Sign up to view the full content.

CS 3110 Recitation 24 Streams and lazy evaluation Introduction : the if construct We have already seen that in OCaml, if true then e1 else e2 evaluates to e1 , while if false then e1 else e2 evaluates to e2 . Actually, in if true then e1 else e2 , the value of e2 is never evaluated: this is called a lazy evaluation. We say that if eagerly evaluates condition expression to true or false, and lazily evaluates e1 and e2 . In OCaml, function arguments are eagerly evaluated: the function arguments are evaluated before the function is called. This is not true for every language; for instance in Haskell function arguments are lazily evaluated. Also in OCaml, function bodies are lazily evaluated: fun x->e is considered a value, and no attempt is made to evaluate the value of e : function bodies are not evaluated until the function is applied. The example below shows that trying to reprogram an if construct using an eager evaluation always fails: the if construct needs a lazy evaluation! let rec factorial (n : int) : int = if n <= 0 then 1 else n * factorial (n - 1) let my_if ((b, t, f):bool * 'a * 'a) : 'a = if b then t else f (* does not terminate : get to factorial2(0), then tries to evaluate factorial2(-1), factorial2(-2), etc. *) let rec factorial2 (n : int) : int = my_if (n <= 0, 1, n * factorial2 (n - 1)) let if_funs ((b, t, f):bool * (unit->'a) * (unit->'a)): 'a= if b then t() else f() (* factorial2 fixed *) let rec factorial3 (n : int) : int = if_funs (n <= 0, (fun () -> 1), (fun () -> n * factorial3 (n - 1))) Call by value and call by name Let us now look at let constructs and function evaluations. In an eager language like OCaml, these are

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 4

rec24 - CS 3110 Recitation 24 Streams and lazy evaluation...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online