top | item 44236630

(no title)

oneearedrabbit | 8 months ago

Decades ago, a closure in Forth was especially innovative with DOES>:

  : COUNTER
    CREATE ,
    DOES> DUP 1 SWAP +! @ ;
  0 COUNTER PK
  PK .  \ => 1
  PK .  \ => 2
A semi-equivalent in Javascript is:

  const counter = init => {
    let x = init;
    return () => { x += 1; return x; };
  };
  const pk = counter(0);
  console.log(pk());  // => 1
  console.log(pk());  // => 2

discuss

order

No comments yet.