I used only the procedures provided by RnRS, instead of loading SRFI-13,
but you could use string-map if you want to. For those who prefer to roll
their own, here is a simple version of string-map! that mutates the string
in place:

(define (string-map! f str)
  (do ((i 0 (+ i 1))) ((= i (string-length str)) str)
    (string-set! str i (f (string-ref str i)))))

Or you could convert to a list, perform the mapping, and convert back, as I
did in my original version of the function. With string-map!, the caesar
function changes to this:

(define (caesar str n)
  (define (char-plus c)
    (let ((alpha "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
      (if (not (char-alphabetic? c)) c
        (let ((i (- (char->integer (char-upcase c)) 65)))
          (string-ref alpha (modulo (+ i n) 26))))))
  (string-map! char-plus str))

For purposes of Rosetta Code, it's probably better to avoid SRFI-13 and
stay with RnRS, as in my first version of the function.


On Mon, Mar 10, 2014 at 10:31 AM, Peter Bex <peter....@xs4all.nl> wrote:

> On Mon, Mar 10, 2014 at 10:26:56AM -0500, Phil Bewig wrote:
> > I would use an auxiliary function char-plus to add or subtract an offset
> to
> > a character:
> >
> > (define (caesar str n)
> >   (define (char-plus c)
> >     (let ((alpha "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
> >       (if (not (char-alphabetic? c)) c
> >         (let ((i (- (char->integer (char-upcase c)) 65)))
> >           (string-ref alpha (modulo (+ i n) 26))))))
> >   (list->string (map char-plus (string->list str))))
>
> If you're using srfi-13, you might as well change the final line to use
> string-map:  (string-map char-plus str)
>
> Cheers,
> Peter
> --
> http://www.more-magic.net
>
_______________________________________________
Chicken-users mailing list
Chicken-users@nongnu.org
https://lists.nongnu.org/mailman/listinfo/chicken-users

Reply via email to