Note that there are some explanatory texts on larger screens.

plurals
  1. POSpecial closure use-cases: Why use closures?
    primarykey
    data
    text
    <h2>Update</h2> <p>I am designing an experimental programming language and the question is wether to include closures or just use first-class-functions. To decide this i need realistic use-cases/examples that show the benefit of closures over first-class-functions. I know that you can achieve <em>everything</em> that you can achieve with one of the two <em>without them</em>, but there are several use-cases for e.g. first-class-functions where the code is easier to read (e.g. shorter or not split up into several classes). E.g:</p> <p>Ruby:</p> <pre><code>[1,5,7].map{|x| x*x } [1,'test',3].select{|x| x.kind_of? Integer}.map{|x| x.to_s } big_array.each{ |item| puts item } </code></pre> <p>Without first-class-functions these examples would be a lot more verbose, since you would have to use for-loops or similar things.</p> <p>Now, what use-cases show the usefulness of closures? Even though i use first-class-functions a lot, i really could not come up with good use-cases for closures. Do you have any good use-cases for closures?</p> <h2>Original Post</h2> <p>I dont get why closures bind to <em>variables</em> and not just to <em>values</em>, e.g.:</p> <p>Ruby:</p> <pre><code>x = 5 l = lambda { x } l.call #=&gt; 5 x = 100 l.call #=&gt; 100 </code></pre> <p>Whats the use in referencing variables instead of just referencing the values stored in the variables at the point of definition of the closure? Like in this example:</p> <p>Ruby:</p> <pre><code>x = 5 l = lambda { x } l.call #=&gt; 5 x = 100 l.call #=&gt; 5, not 100 </code></pre> <p>Are there good use-cases where it is necessary to reference <em>variables</em> instead of just the <em>values</em> of those variables at the point of definition of the closure?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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