Esempi di simulazione dello stile lazy tramite funzioni (cioe', usando il fatto che una funzione valuta a se stessa).
Il seguente programma definisce il datatype 'a lazylist, con le sue lazyhead e lazytail, e inoltre contiene due esempi di funzioni che generano liste "infinite":
datatype 'a lazylist = empty | lazycons of (unit -> ('a * 'a lazylist))
fun lazyhead (lazycons f) = primo(f())
and primo (a,b) = a
fun lazytail (lazycons f) = secondo(f())
and secondo (a,b) = b
fun list_nat n = lazycons(fn () => (n,(list_nat (n+1))))
fun times_list (l1 : int lazylist) (l2 :int lazylist) =
lazycons(fn () =>
(lazyhead(l1)*lazyhead(l2) ,
times_list (lazytail l1) (lazytail l2)) )
fun list_fact () = lazycons(fn () =>
(1,(times_list (list_nat 1) (list_fact ()))))
- lazyhead (list_nat 5);
val it = 5 : int
- lazyhead (lazytail (list_nat 5));
val it = 6 : int
- lazyhead (list_fact ());
val it = 1 : int
- lazyhead(lazytail(list_fact ()));
val it = 1 : int
- lazyhead(lazytail(lazytail(list_fact ())));
val it = 2 : int
- lazyhead(lazytail(lazytail(lazytail(list_fact ()))));
val it = 6 : int