Character math?

Notices and updates
Locked
hsmyers
Posts: 104
Joined: Wed Feb 20, 2008 4:06 pm
Location: Boise, ID, USA
Contact:

Character math?

Post 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
"Censeo Toto nos in Kansa esse decisse."—D. Gale "ℑ♥λ"—Toto

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post 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.

hsmyers
Posts: 104
Joined: Wed Feb 20, 2008 4:06 pm
Location: Boise, ID, USA
Contact:

Post by hsmyers »

Wow--- I'll have to study this one. Not at all along any lines I had thought about. Cool Lutz, thanks!

--hsm
"Censeo Toto nos in Kansa esse decisse."—D. Gale "ℑ♥λ"—Toto

Locked