Reputation: 375
I'm studying functional programming in racket, and a question test said:
In Java we can increment a varible using x += 10;
Can we define a function in Racket (+= var amount)
with the same meanings of Java?
I'm not really sure, but I think no because I can't modify a variable with a function in racket.
Like:
(define myvar 10)
(+= myvar 1)
myvar
I'm keep getting 10, when I type myvar
in the drracket console
Upvotes: 1
Views: 527
Reputation: 48745
Basically x += 5
are short for x = x + 5
in most Algol languages. In Java I'm sure you cannot do what you are asking for. eg.
public static void method plusEqual(int binding, int increment) {
binding = binding + increment;
}
However in Scheme and Racket you can. Since the full form is (set! binding (+ binding argument))
I'm suggesting +set!
(define-syntax +set!
(syntax-rules ()
((_ binding increment)
(set! binding (+ binding increment)))))
(define test 10)
(+set! test 5)
test ; ==> 15
Upvotes: 4
Reputation: 1028
You cannot define a function to do this.
You can define a macro that expands to (set! var (+ var amount))
though, and that'll do it!
Upvotes: 1