Reputation: 146
I am trying to create a recursive function which picks n items from a list returning the picked values and the list without the values, but when I create my variables I get this error:
new-list: unbound identifier in: new-list
Here is my code:
(define(pick-randomr list n picked) ;;Picked always called as empty list
(if(= n 0) (values list picked)
((let* ([aux list]
[r (random (length aux))]
[value (list-ref aux r)]
[new-picked (cons value picked)]
[new-list (values (remove value aux))])
(values aux r new-list))
(pick-randomr new-list (- n 1) new-picked))))
EDIT: The line that goes:
(values aux r new-list)
is just to not have an empty body
Upvotes: 0
Views: 159
Reputation: 236004
There are a couple of problems with your syntax:
list
as a parameter name, it conflicts with a built-in procedure of the same name.let*
with two brackets, that's a common mistake, brackets are not like curly braces in other languages, you must not use them to define a block of statements, use begin
for that - but we don't need it in this particular case.let*
with an empty body. But the expression you added there isn't right, you must write the expressions that use the variables inside the let*
, otherwise the new-list
variable won't be visible.This is what you meant to write:
(define (pick-randomr lst n picked)
(if (= n 0)
(values lst picked)
(let* ([aux lst]
[r (random (length aux))]
[value (list-ref aux r)]
[new-picked (cons value picked)]
[new-list (values (remove value aux))])
(pick-randomr new-list (- n 1) new-picked))))
Let's test it:
(pick-randomr '(1 2 3 4 5) 2 '())
=> '(1 2 5)
'(3 4)
Upvotes: 1