Skip to content

Instantly share code, notes, and snippets.

@clarkema
Created March 6, 2016 14:54
Show Gist options
  • Select an option

  • Save clarkema/f04c78266809cb9b3311 to your computer and use it in GitHub Desktop.

Select an option

Save clarkema/f04c78266809cb9b3311 to your computer and use it in GitHub Desktop.

Revisions

  1. clarkema created this gist Mar 6, 2016.
    25 changes: 25 additions & 0 deletions State closures
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    ;; Lisp

    (defun counter ()
    (let ((i 0))
    (lambda () (incf i))))

    (setf indexer (counter))

    (funcall indexer) => 1
    (funcall indexer) => 2
    (funcall indexer) => 3

    # Perl

    sub counter {
    my $i = 0;
    return sub {++$i};
    }

    my $indexer = counter();
    print $indexer->(); # 1
    print $indexer->(); # 2
    print $indexer->(); # 3