Note that there are some explanatory texts on larger screens.

plurals
  1. POusing callCC with higher-order functions in R
    text
    copied!<p>I'm trying to figure out how to get R's callCC function for short-circuiting evalutation of a function to work with functions like lapply and Reduce.</p> <p><strong>Motivation</strong></p> <p>This would make Reduce and and lapply have asymptotic efficiency > O(n), by allowing you to exit a computation early.</p> <p>For example, if I'm searching for a value in a list I could map a 'finder' function across the list, and the second it is found lapply stops running and that value is returned (much like breaking a loop, or using a return statement to break out early).</p> <p>The problem is I am having trouble writing the functions that lapply and Reduce should take using a style that callCC requires.</p> <p><strong>Example</strong></p> <p>Say I'm trying to write a function to find the value '100' in a list: something equivalent to</p> <pre><code>imperativeVersion &lt;- function (xs) { for (val in xs) if (val == 100) return (val) } </code></pre> <p>The function to pass to lapply would look like:</p> <pre><code>find100 &lt;- function (val) { if (val == 100) SHORT_CIRCUIT(val) } functionalVersion &lt;- function (xs) lapply(xs, find100) </code></pre> <p>This (obviously) crashes, since the short circuiting function hasn't been defined yet.</p> <pre><code>callCC( function (SHORT_CIRCUIT) lapply(1:1000, find100) ) </code></pre> <p>The problem is that this also crashes, because the short circuiting function wasn't around when find100 was defined. I would like for something similar to this to work.</p> <p>the following works because SHORT_CIRCUIT IS defined at the time that the function passed to lapply is created.</p> <pre><code>callCC( function (SHORT_CIRCUIT) { lapply(1:1000, function (val) { if (val == 100) SHORT_CIRCUIT(val) }) ) </code></pre> <p>How can I make SHORT_CIRCUIT be defined in the function passed to lapply without defining it inline like above?</p> <p>I'm aware this example can be achieved using loops, reduce or any other number of ways. I am looking for a solution to the problem of using callCC with lapply and Reduce in specific.</p> <p>If I was vague or any clarification is needed please leave a comment below. I hope someone can help with this :)</p> <p>Edit One: The approach should be 'production-quality'; no deparsing functions or similar black magic. </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