Dan D.
Dan D.

Reputation: 8557

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)

Upvotes: 1

Views: 137

Answers (1)

Sorawee Porncharoenwase
Sorawee Porncharoenwase

Reputation: 6502

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)

Upvotes: 2

Related Questions