方案中的随机函数

发布于 2024-10-01 19:06:34 字数 844 浏览 4 评论 0原文

我正在尝试从方案中的字符串列表中获取随机字符串。 示例列表(“这个”“那个”“今天”“昨天”) 因此,根据列表的长度创建一个随机数并输出该单词。但不断出错!

我这样尝试:

;; 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 中,我会使用数组并直接给出位置。 无论如何也要在计划中做到这一点吗?

I am trying to get a random string from a list of strings in scheme.
Example List ( "this" "that" "today" "yesterday")
So based on length of the list a random number is created and that word is output. But keep getting error!

I tried it like this:

;; 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))]))

Error:

procedure application: expected procedure, given: 
("this" "that" "today" "yesterday") (no arguments)

When I try to do :

(random-function (random (length list)) 

on the console I get a random number.

Do not understand why it is crashing here when done inside my program???

Could I do this in a better way rather than looping so many times.
In Java I would have used an array and given the position directly.
Anyway to do it in scheme too ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笑叹一世浮沉 2024-10-08 19:06:34
(define (random-element list)
  (list-ref list (random (length list))))
(define (random-element list)
  (list-ref list (random (length list))))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文