Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Let's look at the classic add-n closure from <a href="https://stackoverflow.com/questions/36636/what-is-a-closure">What is a closure</a>.</p> <pre><code>(define (add a) (lambda (b) (+ a b))) (define add3 (add 3)) (add3 4) returns 7 </code></pre> <p>In the above lambda expression, <code>a</code> is the <a href="http://en.wikipedia.org/wiki/Free_variables_and_bound_variables" rel="nofollow noreferrer">free variable</a>, which is defined in the Wikipedia link to be:</p> <blockquote> <p>a variable referred to in a function that is not a local variable or an argument of that function. An upvalue is a free variable that has been bound (closed over) with a closure.</p> </blockquote> <p>Coming back to</p> <pre><code>def filesEnding(query: String) = filesMatching(_.endsWith(query)) </code></pre> <p>The implicit function <code>x =&gt; x.endsWith(query)</code> is the first-class function, which is assigned to first-class value <code>matcher</code>, and <code>_.endsWith()</code> is closed over <code>query</code>, similar to the way 3 closes up <code>a</code> in <code>(add 3)</code>. <code>(add3 4)</code> equivalent is done by <code>matcher(file.getName)</code>. </p> <p><strong>Edit</strong>: Tricky part is the feature in Scala called placeholder syntax anonymous functions. By using <code>_</code> in place of the sender or the parameter, Scala automatically creates an anonymous function, which we can consider it as lambda expression.</p> <p>For example,</p> <pre><code>_ + 1 creates x =&gt; x + 1 _ * _ creates (x1, x2) =&gt; x1 * x2 _.endsWith(query) creates x =&gt; x.endsWith(query) </code></pre> <p>Within the function <code>x =&gt; x.endsWith(query)</code>, <code>query</code> meets the two requirements of being a free variable:</p> <ol> <li><code>query</code> is not a local variable defined within the function (there is no local variable).</li> <li><code>query</code> is not an argument of the function (the only argument is <code>x</code>).</li> </ol>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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