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: Martin Jambon <martin.jambon@e...>
Subject: Re: [Caml-list] lazy vs fun
Stéphane Glondu wrote:
> Warren Harris a écrit :
>> Is there any advantage to using lazy evaluation in ocaml rather than
>> just using thunks to defer evaluation? [...]
> 
> Two things I can think of right now: they are evaluated only once (even
> if you call Lazy.force several times), and you can do pattern matching
> with them.


Note that the memoization feature can be implemented like this:

let lz f =
  let result = ref `None in
  fun () ->
    match !result with
        `None ->
          (try
	     let y = f () in
             result := `Result y;
	     y
           with e ->
	     result := `Exn e;
	     raise e
	  )
      | `Result y -> y
      | `Exn e -> raise e


# #load"unix.cma";;
# let first_date = lz Unix.gettimeofday;;
val first_date : unit -> float = <fun>
# first_date ();;
- : float = 1251151837.4585979
# first_date ();;
- : float = 1251151837.4585979


However this is slightly less efficient than how "lazy" is implemented, and of
course you don't have the nice syntax nor the (recent) pattern matching feature.



Martin

-- 
http://mjambon.com/