我需要在方案中生成一个随机的ASCII字母(大写或小写)或字符(但不是数字),我想知道适当的方法是什么。目前我已经获得了代码
(define a 1)
(define b 16)
(define (s8 a b)
(when (<= a b)
(if (= (mod a 8) 0)
(write "h")
(write a))
(s8 (+ a 1) b)))
(s8 a b)
有效(没有错误)但是我没有打印随机的ascii字母/字符,而是因为我不知道如何做到这一点。我用Google搜索,但无法找到任何东西。任何帮助,将不胜感激。谢谢!
编辑:
(define random-char
(let* ((chars '("a" "e" "i" "o" "u"))
(len (length chars)))
(lambda ()
(list-ref chars (random len)))))
(define a 1)
(define b 16)
(define (s8 a b)
(when (<= a b)
(if (= (mod a 8) 0)
(random-char)
(write a))
(s8 (+ a 1) b)))
(s8 a b)
给出错误
1234567
Error: execute: unbound symbol: "random" [s8, s8, s8, s8, s8, s8, s8, s8, random-char]
答案 0 :(得分:1)
一种简单的方法是将所有可接受的字符放在一个列表中,然后随机选择一个:
(define random-letter
; this is to avoid redefining the list of acceptable letters every time
(let* ((chars '("a" "e" "i" "o" "u"))
; and this is to pre-calculate the length
(len (length chars)))
(lambda () ; the actual procedure, it doesn't require arguments
(list-ref chars (random len))))) ; pick a random index from list
确保在列表中添加所有需要的字符。使用该程序就像这样简单:
(random-letter)
=> "u"
答案 1 :(得分:0)
以下是如何使用工业强度的Scheme派生语言:特别是Racket。它假定了各种功能 您可能需要在更简单的Scheme中实现,例如函数 制作字符串,在字符和整数之间进行转换,以及PRNG (以及咖喱)。
如果您的方案缺少某些功能,您可能需要编写它,这可能在教育上很有趣,但没有别的。
(define latin-alpha-string
;; This assumes that a-z are a sequence of adjacent, increasing
;; character codes, as are A-Z, but nothing about their relative values
(let ([lca (char->integer #\a)]
(uca (char->integer #\A)))
;; build-string makes a string by calling a function which takes an index
;; and returns the character at that index.
(build-string (+ 26 26)
(λ (i)
(integer->char
(if (< i 26)
(+ lca i)
(+ uca (- i 26))))))))
(define (random-string-char s (rand random))
;; The general case: return a random element of a string. rand, if provided,
;; should be a function of one argument, i, which returns a (pseudo-)random
;; integer in [0, i).
(string-ref s (rand (string-length s))))
(define random-latin-alpha-char
;; and here's a curried version of the above for latin-alpha strings
(curry random-string-char latin-alpha-string))