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))))

Then here are your two examples; decryption is just encryption by the
negative:

> (caesar "To craunch the marmoset." 1)
"UP DSBVODI UIF NBSNPTFU."
> (caesar "UP DSBVODI UIF NBSNPTFU." -1)
"TO CRAUNCH THE MARMOSET."


On Mon, Mar 10, 2014 at 9:51 AM, Daniel Carrera <dcarr...@gmail.com> wrote:

> Hello,
>
> I found a Scheme implementation of the Caesar cipher on Rosetta Code. It
> said "This was written by a novice, please review"... So I reviewed it, and
> basically rewrote it.
>
> I think my version is much better (clearer) but since I too am a novice, I
> feel bad removing the "novice" warning. Could someone who has used Scheme
> longer than two weeks have a quick look at my work and tell me if I can
> remove the warning (or make corrections if my code is not idiomatic or
> something)?
>
> My version(s):
>
> http://rosettacode.org/wiki/Caesar_cipher#Scheme
>
> Previous version:
>
> http://rosettacode.org/mw/index.php?title=Caesar_cipher&oldid=177675#scheme
>
> Cheers,
> Daniel.
> --
> When an engineer says that something can't be done, it's a code phrase
> that means it's not fun to do.
>
> _______________________________________________
> Chicken-users mailing list
> Chicken-users@nongnu.org
> https://lists.nongnu.org/mailman/listinfo/chicken-users
>
>
_______________________________________________
Chicken-users mailing list
Chicken-users@nongnu.org
https://lists.nongnu.org/mailman/listinfo/chicken-users

Reply via email to