Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Welcome to the wonderful world of closures! This is a textbook example of how closures in Scheme work.</p> <p>So <code>make-counter</code> returns a function that has 3 variables that it captures from it's enclosing environment: <code>n</code>, <code>old</code>, <code>new</code>. In this case, the starting environment looks something like</p> <pre><code>_name_|_value_ n | 3 old | 0 new | 1 </code></pre> <p>On each invocation, it increments <code>old</code> and <code>new</code> and wraps them around if they're greater than <code>n</code>. Because it's using <code>set!</code>, this incrementing is mutating the variables in the lambda's environment, but since these variables are captured from the surrounding environment, they are changed for all future calls as well.</p> <p>That's why you get different returns even with the same input.</p> <p>If this seems like witchcraft, you can think of it like objects in more common languages:</p> <p>Eg Python:</p> <pre><code>class Foo(): def __init__(self, n, m): self.n = n self.m = m def count(self): self.n += 1 if self.n == self.m: self.n = 1 return self.n-1 f = Foo(0, 2) f.count() # 1 f.count() # 0 </code></pre> <p>This is the same basic idea except here we're being a bit more explicit about where the environment is coming from, <code>self</code>. In Scheme, we mimic this with the lambda capturing the surrounding variables.</p> <p>For more, check out <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-19.html#%_chap_3" rel="nofollow">SICP</a></p>
    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