Last active
October 4, 2017 16:19
-
-
Save dockimbel/79237c5454481bcb7d68105281b142a8 to your computer and use it in GitHub Desktop.
"Capture by value" closure generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Red [ | |
Purpose: {Implementation of a "capture-by-value" closure generator} | |
Date: 4-Oct-2017 | |
] | |
collect-words: function [ | |
spec [any-list!] | |
/deep | |
/set | |
/to-set | |
/ignore | |
list [block! any-object! none!] | |
return: [block!] | |
][ | |
if any-object? list [words: words-of list] | |
collect [ | |
foreach w spec [ | |
case [ | |
any-word? w [ | |
unless all [list find list to word! w][ | |
if any [all [set set-word? w] not set][ | |
keep to any [all [to-set set-word!] word!] w | |
] | |
] | |
] | |
all [deep any-list? w][keep collect-words w] | |
] | |
] | |
] | |
] | |
closure: func [spec [block!] body [block!] /local list pos rule v fun][ | |
list: unique collect [ | |
parse body rule: [ | |
any [ | |
pos: word! (keep pos/1) | |
| any-path! (keep pos/1/1) | |
| ahead any-list! into rule | |
| skip | |
] | |
] | |
] | |
list: exclude list collect-words spec | |
list: collect [foreach w list [keep to-set-word :w keep attempt [get :w]]] | |
bind body-of fun: func spec body construct/only list | |
:fun | |
] | |
;--- Test case --- | |
comment [ | |
closing: func [/local a][ | |
a: 1 | |
cPrint: closure [][print a] | |
cAdd1: closure [][a: a + 1] | |
cPrint | |
cAdd1 | |
cPrint | |
] | |
closing | |
cAdd1 | |
cPrint | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment