News for hackers. Stuff that matters.
Re:All About E: The Language That Infiltrated JavaScript by kragen on Thursday October 27, 2022 @01:22PM (#33360892)
This function creates a closure with a private variable, "n". When invoked the closure will increase n by the specified amount, but there is no way to decrease it.

    const incfac = () => { let n = 0; return m => (m > 0 ? n += m : n) };
A more extensive example due to Norm Hardy, presuming a multiuser Scheme interpreter that supports ocap security, is this Scheme program for voting on where to have lunch: http://cap-lore.com/CapTheory/Language/Lunch.html

    (define (mocntr) (let ((x 0)) (cons (lambda () (let ((yet #t))
         (lambda () (if yet (begin (set! yet #f) (set! x (+ 1 x)) x)))))
      (lambda () x))))
    (define lunchcrowd (list (lambda (x) (write (cons "for Bill" x)))
       (lambda (x) (write (cons "for Bob" x))
              ((cdr (assoc "Mandarin" (cdr x)))))))
    (define restaurants (list "Mandarin" "Casa Lupe" "Coffee Shop"))
    (define (noontime) (let ((bb
           (map (lambda(r) (cons r (mocntr))) restaurants)))
        (for-each (lambda (e) (e (cons "Lunchtime!" (map
          (lambda(r)(cons (car r) ((cadr r)))) bb)))) lunchcrowd)
        (lambda ()(map (lambda(x) (cons (car x) ((cddr x)))) bb))))
Norm explains:

> An invocation of mocntr is made each day for each restaurant. It returns a source of options, one of which will be offered to each of the lunch crowd. The second lambda in the definition produces such an option. The variable yet in that proc remembers if the option has been taken. The third lambda produces the getter for the count.

> bb is created each day for lunch and constitutes the ballot box. It is a list of pairs <restuarant name, <option source, count getter>>. This list is iterated over first to send each vote solicitation, and then later to count the votes.

Unfortunately he's vitrified now, so if you send him questions he will answer after a long delay, if ever.

There are no comments on this comment yet.