SML is a strict (eager) language.
It is however possible to implement laziness in new datatypes.
- A lazy language such as
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
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:|
| :: || cons |
| [x1,...] || list |
| [ ] || list |
| @ || append |
| fn => || &lambda . |
| : || has type |