Search code examples
incrementchicken-scheme

Scheme's version of C's `++`


How would I go about incrementing a variable, that is doing something like a=0; a++; in Chicken?

In Common Lisp I'd do this using incf like so:

(setf a 0) (incf a) (print a)

;=> 0

;=> 1

;=> 1
;=> 1

But Chicken-scheme doesn't seem to have a incf function/macro, and I've tried using the apropos egg thingy, but that hasn't helped at all so far.

In C, I'd increment the variable like so:

int a = 0;
a++;
printf("%d", a);

NOTE, I don't want to know how to simply increase the value of a temporarily by 1, I want to increment a so that a no longer equals 0 but equals 1.

Thus, the following is NOT what I want:

(let ((a 0)) (set! a (+ 1 a)) (print a))

Here's an example of what I'm looking for--written in NewLisp:

(set 'a 0) (++ a) (println a)

NOTE The function/macro needs to be able to accept a quoted variable and increment that variables value, permanently. Thus it needs to be equivalent to the following C code:

a = 0; a++; // a now equals 1

I'd just write a macro to do this in Chicken, but I can't seem to make heads or tails of the Chicken's macros--they just don't make any sense; they're nothing like common-lisps macros at all.

Here's an example macro that I just hacked together in common-lisp:

(defmacro ++ (sym) (let ((a (gensym "a,sym,") ))
  `(let* ((,a ,sym))
      (setf ,sym (+ 1 ,a)) ,sym)) )

(setf a 0)

;=> 0

(++ a)

;=> 1

a 

;=> 1

Solution

  • Setting things is done with set! in Scheme.

    (let ((a 0))
      (set! a (+ a 1))
      (print a))
    

    I am not a Schemer, but I think you can write a macro for this like the following:

    (define-syntax inc!
      (syntax-rules ()
        ((inc! var)
         (set! var (+ var 1)))))
    

    so that you can then write

    (inc! a)