Just to understand how the Scheme macros work i’m trying to define a new command, sum that works exactly like the common operator + (i.e. also undefined number of parameters).
I wroter this code:
(define-syntax sum
(syntax-rules ()
((_ arg1 arg2 args...)
(sum (+ arg1 arg2) args...))
((_ arg1 arg2)
(+ arg1 arg2))
((_ arg1)
arg1)))
It works if i pass it 1, 2 or 3 arguments. But with 4 arguments i get this error:
sum: bad syntax in: (sum 1 2 3 4)
I tried to expand the macro step-by-step with DrRacket but it stops immediately.
Can someone explain me the cause of this error?
In Scheme,
...is just another identifier, so you need a space betweenargsand the ellipses (...) in both places, like this:BTW, you don’t need to create macros in order to accept arbitrary numbers of arguments. You can also use “rest args”: