2016-12-24 149 views
1

我需要在方案中生成一个随机的ASCII字母(大写或小写)或字符(但不是数字),我想知道做什么的适当方法是。目前,我已经得到了代码生成随机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字母/字符,我得到的“H”,因为我不知道该怎么做。我搜索了一下,但找不到东西。任何帮助,将不胜感激。谢谢!

编辑:

(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

不要重新发明轮子! Scheme具有用于生成随机值的内置过程。 –

回答

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" 
+0

我把定义放在开头,然后用'(随机字母)'代替'(写入“h”),并给出了错误'1234567 错误:execute:unbound symbol:“random”[s8, s8,s8,s8,s8,s8,s8,s8,random-char]'。 – heather

+0

这意味着你的解释器没有“随机”过程或命名不同。你在用什么解释器?检查文档以找到正确的程序使用,或者下载球拍,这非常适合学习。另外,我不确定如何执行代码,显示的输出没有意义 - 您应该清除所有内容,然后复制粘贴上述代码片段 –

+0

我正在使用repl.it,一个在线解释器。它说:“BiwaScheme解释器版本0.6.4 Copyright(C)2007-2014 Yutaka HARA和BiwaScheme团队”。我编辑了我跑的代码。 – heather

0

这里是你可能会怎么做这在工业强度的计划衍生的语言:特别是球拍。它假定你可能需要在一个更简单的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))