3
我想從方案中的字符串列表中獲取一個隨機字符串。 示例列表(「this」「that」「today」「yesterday」) 因此,根據列表的長度創建一個隨機數並輸出該字。但不斷收到錯誤!方案中的隨機函數
我想它是這樣的:
;; produces random number that should be input to the random-function
(define (random-num list)
(random-function ((random (length (list))) list)))
;; loops the number of times till random number is 0 and outputs the list value
(define (random-function num list)
(cond
[(zero? num) (car list)]
[else (random-function (- num 1) (cdr list))]))
錯誤:
procedure application: expected procedure, given:
("this" "that" "today" "yesterday") (no arguments)
當我嘗試這樣做:
(random-function (random (length list))
控制檯我得到一個隨機數上。
不明白爲什麼它在我的程序內完成時崩潰?
我能否以更好的方式來做到這一點,而不是循環太多次。 在Java中我會使用一個數組並直接給定位置。 無論如何也在計劃中做到這一點?
你真棒! list-ref真棒!看起來好於數組:) – JJunior 2010-11-13 21:47:21
好吧,如果你有很大的列表,向量仍然更好,否則差異可以忽略不計。 – 2010-11-13 22:10:38
矢量更好,因爲你可以立即跳轉到元素'n',而列表你必須從頭開始,並找到你的方式來元素'n'。 – erjiang 2010-11-14 03:12:48