Page 1 of 1

Character math?

Posted: Sun Mar 23, 2008 8:38 pm
by hsmyers
What is the fastest way to increment/decrement a character? At the moment I'm looking at

Code: Select all

(define (incr-char c)
	(char (+ (char c) 1)))

(define (decr-char c)
	(char (- (char c) 1)))

While it works, I've got my doubts--- I'm fairly sure it could be made better. I noticed the code for ++ and I am thinking about the ability to change the original as well as just return char + 1 etc. In assembler this is either a 'inc' or 'dec' on the dereferenced pointer and it bothers me that I don't have something similar. What say you all?

--hsm

Posted: Mon Mar 24, 2008 12:51 am
by Lutz
You can do it like this:

Code: Select all

(define (inc-char:inc-char init)
    (char (if init 
        (set 'inc-char:char init) 
        (inc 'inc-char:char)))) 

> (inc-char 65) ; initialize
"A"
> (inc-char)
"B"
> (inc-char)
"C"
> (inc-char)
"D"
> 
This function keeps state in its own namespace, and is also faster.

Posted: Mon Mar 24, 2008 2:09 am
by hsmyers
Wow--- I'll have to study this one. Not at all along any lines I had thought about. Cool Lutz, thanks!

--hsm