在Scheme中随机列出 [英] Making a random list in Scheme

查看:90
本文介绍了在Scheme中随机列出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想随机列出一个列表,并在更大的功能中使用它.

I am just trying to randomly make a list and use it in a larger function.

        (define make-random-list
        (if
          (= (random 2) 0) (list 2 3)
                           (list 3 2)))

这只会产生列表(2 3),我不确定为什么.是什么原因造成的?

This only produces the list (2 3) and I am not sure why. What is happening to cause this?

如果我这样写,就可以使该功能正常工作

I can make the function work if I write it like this

  (define make-random-list
   (lambda (x)
   (if
    (= (random x) 0) (list 2 3)
                     (list 3 2))))

并调用(make-random-list 2)

and calling (make-random-list 2)

但是我不明白为什么这样行得通,而另一个人行不通.不允许第一个函数产生随机结果的方案怎么了?

but I do not understand why that would work and the other one would not. What is going on with scheme that would not allow the first function to produce random results?

推荐答案

在您的第一个代码段中,您将一次性计算的结果分配给变量.您在这里需要定义一个函数,该函数在每次调用时都会进行评估.您的第二个片段完全可以做到这一点,但是有一种较短的表达方式:

In your first snippet, you're assigning the result of a one-time computation to a variable. What you need here is to define a function that will be evaluated every time it's invoked. Your second snippet does exactly that, but there is a shorter way to express the same:

(define (make-random-list x)
(if
  (= (random x) 0) (list 2 3)
                   (list 3 2)))

请注意语法上的区别:函数定义将函数定义与形式参数名称一起括在括号中,而变量名周围没有括号.

Note the difference in the syntax: a function definition encloses the function definition together with the formal argument names in parentheses, while there are no parentheses around the name of a variable.

这篇关于在Scheme中随机列出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆