如何从球拍的单词列表中选择一个随机单词?

How to choose a random word from a list of words in racket?

我想从单词列表中随机选择一个单词,并可能将其隐藏在 * 中。我是全新的,在练习 python 后发现很难在 racket 中创建代码。我试过的代码是-

(定义(随机词) (列表参考 词表 (length list-of-words (make-string (random 10) #*))))

然后-

(random-word) . . length: arity mismatch; the expected number of arguments does not match the given number expected: 1 given: 2

如果我写这个- (定义(随机词) (列表参考 词表 (取模 (合同随机生成(or/c 精确非负整数?)) (长度单词列表)))) 然后- 合同随机生成未定义。

我实际上只是在尝试随机代码,看看事情是否可行,但无论如何我都做不到。

一种简单但不是很有效的方法是使用 shuffle 并取结果的第一个元素。

(define (random-word lst) (first (shuffle lst)))

更好的方法是 generate a random number in the range [0, length of list), and use list-ref 到 return 该元素。它最终不会比上面的版本长很多:

(define (random-word lst) (list-ref lst (random (length lst))))

I am actually just trying random codes to see if things work out or not but in any way I can't.

所谓的Cargo cult programming应该不惜一切代价避免。你在欺骗自己的理解和合理的推理技术来从根本上解决问题。

(define (hide-random-elem ls)
  (let ((len (length ls)))
    (let loop ((ls ls) (ref (random 0 len)))
      (if (= ref 0)
          (cons '* (cdr ls))
          (cons (car ls) (loop (cdr ls) (- ref 1)))))))
(define my-list '(a b c d e f g h i j k l m n o))

(hide-random-elem my-list)
'(a b c d e f g h i j k l * n o)
(hide-random-elem (hide-random-elem (hide-random-elem my-list)))
'(* b c d e f g h i * k l m n *) ; may or may not contain 3 *'s

推荐阅读