遍历 Racket 中的字母 [英] Iterate through the letters of the alphabet in Racket
问题描述
我想编写一个程序,将字母表中的字母作为符号进行迭代,并对它们进行处理.我希望它大致相当于这个 C 代码:
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);
}
我真的不知道如何在 Racket 中做到这一点.感谢您的帮助.
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))
你可以用 for
循环做更多的事情.例如,
You can do a lot more with for
loops though. For example,
(for/list ([let alphabet] [r-let (reverse alphabet)])
(list let r-let))
生成一个字母列表,与另一个方向的字母配对.虽然这实际上用地图表示更好:(map list letter (reverse letters))
.
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))
.
此外,SRFI-14 提供了更多操作如果您需要更多字符集.
Also, SRFI-14 provides more operations over sets of characters if you need more.
最初,我用 char->integer
、integer->char
和 range
做了一些事情,但我有现在更简单了.
Originally, I did something with char->integer
, integer->char
, and range
but what I have now is simpler.
这篇关于遍历 Racket 中的字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!