Question

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
Was it helpful?

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)

OTHER TIPS

(define counter
        (let ((count 0))
          (lambda ()
            (set! count (+ count 1))
            count)))

>(counter)
1
>(counter)
2

Always keep the scope of your side-effects contained within closures. the count variable can't escape the let scope

EDIT: please look at the following. (Although it is exactly what you should try to usually avoid!)

> (define a 0)
> (define inca (lambda () (set! a (+ a 1))))
> a
0
> (inca)
> a
1

SICP is a great book. You should try and understand the scope of variables in scheme and how it differs from other lisps. And being chicken scheme has NOTHING to do with these questions. Chicken is a great R5RS implementation and your questions would apply to all schemes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top