Version française
Home     About     Download     Resources     Contact us    
Browse thread
lazy vs fun
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jake Donham <jake@d...>
Subject: Re: [Caml-list] lazy vs fun
On Mon, Aug 24, 2009 at 2:57 PM, Warren Harris<warren@metaweb.com> wrote:
> Is there any advantage to using lazy evaluation in ocaml rather than just
> using thunks to defer evaluation? E.g.
>
> let x = lazy (3+4)
> let y = Lazy.force x
>
> vs:
>
> let x = fun () -> 3+4
> let y = x ()

Lazy cells don't just defer, they also memoize the returned value once
the cell is forced.

  # let x = lazy (print_endline "forced"; 1);;
  val x : int lazy_t = <lazy>
  # Lazy.force x;;
  forced
  - : int = 1
  # Lazy.force x;;
  - : int = 1

They even memoize exceptions:

  # let x = lazy (print_endline "forced"; failwith "failed");;
  val x : 'a lazy_t = <lazy>
  # Lazy.force x;;
  forced
  Exception: Failure "failed".
  # Lazy.force x;;
  Exception: Failure "failed".

Jake