<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 2.0.26">
<title>Lazy</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700">
<link rel="stylesheet" href="./asciidoctor.css">
<link rel="stylesheet" href="./mlton.css">

</head>
<body class="article">
<div id="mlton-header">
<div id="mlton-header-text">
<h2>
<a href="./Home">
MLton
20241230+git20251029+dfsg-5
</a>
</h2>
</div>
</div>
<div id="header">
<h1>Lazy</h1>
</div>
<div id="content">
<div class="paragraph">
<p>In a lazy (or non-strict) language, the arguments to a function are
not evaluated before calling the function.  Instead, the arguments are
suspended and only evaluated by the function if needed.</p>
</div>
<div class="paragraph">
<p><a href="StandardML">Standard ML</a> is an eager (or strict) language, not a lazy
language.  However, it is easy to delay evaluation of an expression in
SML by creating a <em>thunk</em>, which is a nullary function.  In SML, a
thunk is written <code>fn () =&gt; e</code>.  Another essential feature of laziness
is <em>memoization</em>, meaning that once a suspended argument is evaluated,
subsequent references look up the value.  We can express this in SML
with a function that maps a thunk to a memoized thunk.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="sml">signature LAZY =
   sig
      val lazy: (unit -&gt; 'a) -&gt; unit -&gt; 'a
   end</code></pre>
</div>
</div>
<div class="paragraph">
<p>This is easy to implement in SML.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="rouge highlight"><code data-lang="sml">structure Lazy: LAZY =
   struct
      fun lazy (th: unit -&gt; 'a): unit -&gt; 'a =
         let
            datatype 'a lazy_result = Unevaluated of (unit -&gt; 'a)
                                    | Evaluated of 'a
                                    | Failed of exn

            val r = ref (Unevaluated th)
         in
            fn () =&gt;
               case !r of
                   Unevaluated th =&gt; let
                                       val a  = th ()
                                           handle x =&gt; (r := Failed x; raise x)
                                       val () =         r := Evaluated a
                                     in
                                       a
                                     end
                 | Evaluated a =&gt; a
                 | Failed x    =&gt; raise x
         end
   end</code></pre>
</div>
</div>
</div>
</body>
</html>