Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through the letters of the alphabet in Racket

Tags:

scheme

racket

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.

like image 216
Daniel Avatar asked Dec 04 '22 04:12

Daniel


1 Answers

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.

like image 100
Asumu Takikawa Avatar answered Feb 01 '23 17:02

Asumu Takikawa