简体   繁体   中英

Change variable outside of lambda in Scheme/Racket

The examples from the doc of Racket come with lambda always:https://docs.racket-lang.org/syntax/Defining_Simple_Macros.html

And my define-syntax-parser is like this:

(require syntax/parse/define)
(define-syntax-parser sp
  [_ #'(lambda (x) (set! x (add1 x)))]
)

(define a 0)
((sp) a)
(display a)

Possible to do something like this (remove the lambda )?

(require syntax/parse/define)
(define-syntax-parser sp
  [(f x) #'(set! x (add1 x))]
)

(define a 0)
(f a)
(display a)

The result is expected to be 1 but it's still 0 . And Scheme/Racket don't pass by reference(?!), so how to change those variables outside of lambda?

There's a related answer here: https://stackoverflow.com/a/8998055/5581893 but it's about the deprecated define-macro ( https://docs.racket-lang.org/compatibility/defmacro.html )

Macro can expand to anything, not just lambda .

#lang racket

(require syntax/parse/define)

(define-simple-macro (sp x:id) (set! x (add1 x)))

(define a 0)
(sp a)
(display a)

Or if you prefer to use define-syntax-parser :

#lang racket

(require syntax/parse/define)

(define-syntax-parser sp
  [(_ x:id) #'(set! x (add1 x))])

(define a 0)
(sp a)
(display a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM