Laziness

home
Algorithms
Bioinfo
FP
Logic
MML
Prog.Lang

FP
 SML
  SML97
   Laziness

Also see:
 λ
  e.g.
  Intro
 Haskell

SML is a strict (eager) language. It is however possible to implement laziness in new datatypes.

A lazy language such as λ or Haskell can accept a definition such as
nonNegInts = Cons 0 (map (λ n.n+1) nonNegInts)
-- meaning [0, 1, 2, 3, ...]
but a strict language, such as SML, will reject it because the RHS, `Cons...nonNegInts)' must be evaluated before the binding to the LHS is made, that is before nonNegInts is defined.

The following example shows a well-known technique to implement lists having non-strict tails. The tail is computed by a closure (a function : unit -> 't nList). The "by-need" optimisation is included: If the closure is evaluated the result is saved in the cell, and the saved value is used subsequently. This optimisation requires the use of ref types.


[an error occurred while processing this directive]

It is possible to make the head of the list non-strict by the same technique.

If the tracing print is uncommented and the example run, it is seen that 'first 5 ns' causes 5 tails to be evaluated and 'first 10 ns' only causes a further 5 tails to be evaluated.

window on the wide world:

Computer Science Education Week

Linux
 Ubuntu
free op. sys.
OpenOffice
free office suite,
ver 3.4+

The GIMP
~ free photoshop
Firefox
web browser
FlashBlock
like it says!

SML:
:: cons
[x1,...] list
[ ] list
@ append
fn =>  &lambda .
: has type
Compared

© L. Allison   http://www.allisons.org/ll/   (or as otherwise indicated),
Faculty of Information Technology (Clayton), Monash University, Australia 3800 (6/'05 was School of Computer Science and Software Engineering, Fac. Info. Tech., Monash University,
was Department of Computer Science, Fac. Comp. & Info. Tech., '89 was Department of Computer Science, Fac. Sci., '68-'71 was Department of Information Science, Fac. Sci.)
Created with "vi (Linux + Solaris)",  charset=iso-8859-1,  fetched Wednesday, 20-Sep-2017 19:28:29 AEST.