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)))
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))))
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:
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.
In Scheme, functions are defined by explicitly using a
lambda
like this:Or like this, which is shorthand for the previous syntax and implicitly is using a
lambda
under the hood - both flavors of procedure definition are completely equivalent:The first version of your code wasn't working because this is just assigning the result of the evaluation of
if
to a variable calledmake-random-list
:For defining a procedure in Scheme you have to use a
lambda
, either explicitly or implicitly. So your procedure should be defined using either of this equivalent forms:Notice that you don't have to pass the
x
parameter if the only possible value is2
, simply declare a procedure with no arguments.