Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's something that's almost a direct translation of the same solution strategy.</p> <p>That said, I think there may be a better/simpler representation choice, I'm still mulling it over.</p> <pre><code>type Runner = int -&gt; Result and Result = Result of int * option&lt;Runner&gt; let AddOne = fun x -&gt; Result(x+1, None) let Idle = fun x -&gt; Result(x, None) let rec Pair(r1,r2) = fun x -&gt; match r1 x with | Result(data,None) -&gt; Result(data, Some(r2)) | Result(data,Some(next)) -&gt; Result(data,Some(Pair(next,r2))) let rec Repeat r n = fun x -&gt; if n = 0 then r x else match r x with | Result(data,None) -&gt; Result(data, Some(Repeat r (n-1))) | Result(data,Some(next)) -&gt; Result(data, Some(Pair(next, Repeat r (n-1)))) </code></pre> <p>EDIT</p> <p>Here's another way that's a little more refined... am still trying to see if there's a good way to work in a "list", since the results seem isomorphic to cons cells...</p> <pre><code>type Runner = Runner of (int -&gt; int * option&lt;Runner&gt;) let AddOne = Runner(fun x -&gt; x+1, None) let Idle = Runner(fun x -&gt; x, None) let rec Pair(Runner(r1),R2) = Runner(fun x -&gt; match r1 x with | data,None -&gt; data, Some(R2) | data,Some(next) -&gt; data, Some(Pair(next,R2))) let rec Repeat (Runner(r) as R) n = Runner(fun x -&gt; if n = 0 then r x else match r x with | data,None -&gt; data, Some(Repeat R (n-1)) | data,Some(next) -&gt; data, Some(Pair(next, Repeat R (n-1)))) </code></pre> <p>EDIT</p> <p>One more version, it uses lists, but now I've a feeling for what's weird here...</p> <pre><code>type Runner = Runner of (int -&gt; int * list&lt;Runner&gt;) let AddOne = Runner(fun x -&gt; x+1, []) let Idle = Runner(fun x -&gt; x, []) let rec Pair(Runner(r1),R2) = Runner(fun x -&gt; match r1 x with | data,xs -&gt; data, xs @ [R2]) // inefficient let rec Repeat (Runner(r) as R) n = Runner(fun x -&gt; if n = 0 then r x else match r x with | data,xs -&gt; data, xs @ List.init (n-1) (fun _ -&gt; R)) // inefficient </code></pre> <p>It's almost just like an 'Action queue', a list of <code>int-&gt;int</code> functions. But each guy can produce some 'suffix actions' that run immediately after him (but before the remaining work in the would-be queue), and trying to maintain the ordering with a purely functional data structure is potentially inefficient (without the right tree/queue library at hand). It would be interesting to know how this will be used/consumed, as perhaps a small change there might allow for a completely different strategy.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload