|
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.
|
SML:
:: | cons |
[x1,...] | list |
[ ] | list |
@ | append |
fn => | &lambda . |
: | has type |
Compared
|
|
|