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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With