1

我正在尝试创建一个过程,让用户输入一个非空字符串,然后从长度为 1 的子字符串中的输入中返回一个随机字母。

IE

(pick-at-random "word")

~"w"

(pick-at-random "word")

~"r"

到目前为止,我有:

    (define pick-at-random
      (lambda (s)
        (substring s (random(string-length s)) ())))

这给了我想要显示的字母的位置,我觉得 () 在哪里,我应该有一些变量代表子字符串的起始值,然后向它添加一个。但是,我不知道该怎么做。简而言之,我在问如何在开始值中使用随机函数时将子字符串的长度限制为 1。

4

3 回答 3

2

您可以使用let将随机数绑定到变量。

(define pick-at-random
  (lambda (s)
    (let ((index (random (string-length s))))
      (substring s index (+ index 1)))))
于 2012-09-04T00:48:50.813 回答
1

这是不使用的替代答案substring,这样您就不需要将索引保存在let绑定中。这是解决问题的更实用(因此也是惯用的)解决方案:

(define (pick-at-random s)          ; read the following lines from bottom to top
  (string                           ; convert single character to string
    (string-ref s                   ; access character in string, given an index
      (random (string-length s))))) ; generate a random valid index in the string

(pick-at-random "word")
> "d"   ; random result

前面的过程生成一个随机的有效索引,然后在字符串中的该位置选择字符。作为最后一步,它将单个字符转回长度为 1 的字符串。

于 2012-09-04T02:21:23.667 回答
0

前两个答案很好。或者,您可以将此问题分解为两个问题:

  • 开发函数“nth-char”,它接受一个单词和一个索引,并返回一个包含单词第 n 个字符的字符串。

  • 开发执行您描述的功能“随机选择”。(顺便说一下,我认为像“random-char”这样的名字比“pick-at-random”要好一些。)

这种分解通过将其作为另一个函数的参数来解决您描述的问题。

“Under the hood”,这与使用“let”的解决方案相同。

于 2012-09-04T21:31:08.467 回答