Iterate through the letters of the alphabet in Rac

2019-04-12 18:27发布

问题:

I'd like to write a program that iterates through the letters in the alphabet as symbols and does something with them. I'd like it to be roughly equivalent to this C code:

for(char letter = 'a'; letter <= 'z'; letter++)
{
    printf("The letter is %c\n", letter);
}

I really have no idea how to do this in Racket. Thanks for your help.

回答1:

Assuming that you only want to iterate over lowercase English alphabet letters, here's one way to do it:

(define alphabet (string->list "abcdefghijklmnopqrstuvwxyz"))

(for ([letter alphabet])
  (displayln letter))

You can do a lot more with for loops though. For example,

(for/list ([let alphabet] [r-let (reverse alphabet)])
  (list let r-let))

produces a list of letters paired with letters going the other direction. Although that's actually better expressed as a map: (map list alphabet (reverse alphabet)).

Also, SRFI-14 provides more operations over sets of characters if you need more.

Edit: Originally, I did something with char->integer, integer->char, and range but what I have now is simpler.



回答2:

Just so that one of the answers shows the literal translation approach:

#lang racket
(for ([letter (in-range (char->integer #\a)
                        (add1 (char->integer #\z)))])
  (printf "The letter is ~a\n" (integer->char letter)))

Racket doesn't support the implicit punning between characters and integers that C permits: unlike in C, a Racket value's type is intrinsic rather than external to the value itself. The char->integer and integer->char functions do the explicit translations between those types.



标签: scheme racket