Increment and Decrement operators in scheme programming language
Asked Answered
R

4

10

What are the increment and decrement operators in scheme programming language. I am using "Dr.Racket" and it is not accepting -1+ and 1+ as operators. And, I have also tried incf and decf, but no use.

Rica answered 15/6, 2014 at 10:20 Comment(0)
L
11

They are not defined as such since Scheme and Racket try to avoid mutation; but you can easily define them yourself:

(define-syntax incf
  (syntax-rules ()
    ((_ x)   (begin (set! x (+ x 1)) x))
    ((_ x n) (begin (set! x (+ x n)) x))))

(define-syntax decf
  (syntax-rules ()
    ((_ x)   (incf x -1))
    ((_ x n) (incf x (- n)))))

then

> (define v 0)
> (incf v)
1
> v
1
> (decf v 2)
-1
> v
-1

Note that these are syntactic extensions (a.k.a. macros) rather than plain procedures because Scheme does not pass parameters by reference.

Latakia answered 15/6, 2014 at 11:9 Comment(0)
C
11

Your reference to “DrRacket” somewhat suggests you’re in Racket. According to this, you may already be effectively using #lang racket. Either way, you’re probably looking for add1 and sub1.

-> (add1 3)
4
-> (sub1 3)
2
Caruncle answered 12/8, 2015 at 22:20 Comment(0)
C
2

The operators 1+ and -1+ do /not/ mutate, as a simple experiment in MIT Scheme will show:

1 ]=> (define a 3)
;Value: a
1 ]=> (1+ a)
;Value: 4
1 ]=> (-1+ a)
;Value: 2
1 ]=> a
;Value: 3

So you can implement your own function or syntactic extensions of those functions by having them evaluate to (+ arg 1) and (- arg 1) respectively.

Changeling answered 30/7, 2014 at 7:33 Comment(0)
N
0

It's easy to just define simple functions like these yourself.

;; Use: (increment x)
;; Before: x is a number
;; Value: x+1
(define (increment x)
  (+ 1 x) 
)
Nuclease answered 7/12, 2016 at 19:52 Comment(1)
This will not change that value of variable you are passing. Have a look here: ideone.com/KEgO9gRica

© 2022 - 2024 — McMap. All rights reserved.