2016-12-24 303 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))