In Perl it's possible to generate main-namespace functions like so:
perl -E 'my $z = 1; for (qw/foo bar baz/) {my $x = $_; *$_ = sub{ say "$x:
", $z++ }}; foo(); bar(); baz();'
This outputs:
foo: 1
bar: 2
baz: 3
Note that it is generating top-level subroutines that can be called from
elsewhere in the program (including other modules) and that those
subroutines close over existing lexical variables.
I tried to do this in Racket and haven't been able to figure it out:
First attempt, only partial solution:
$ racket
-> (for ((name '(x y z))) (define name (lambda () (displayln "foo"))))
; /Applications/Racket_v6.3/collects/racket/private/for.rkt:1487:62: begin
; (possibly implicit): no expression after a sequence of internal
definitions
; in: (begin (define name (lambda () (displayln "foo"))))
; [,bt for context]
I found 'eval', but that doesn't close over lexical variables (
https://docs.racket-lang.org/guide/eval.html: "The eval
<https://docs.racket-lang.org/reference/eval.html#%28def._%28%28quote._%7E23%7E25kernel%29._eval%29%29>
function cannot see local bindings"):
$ racket
Welcome to Racket v6.3.
-> (let ((xyz 1)) (for ((name '(x y z))) (eval `(define ,name (lambda ()
(displayln (format "~a: ~a" ,name ,xyz) (set! xyz (add1 xyz))))))))
-> (x)
(x)
; xyz: undefined;
; cannot reference undefined identifier
; [,bt for context]
What have I not found?
--
You received this message because you are subscribed to the Google Groups
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.