0

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

1 Answer 1

1

There are a couple of problems with your syntax:

  • You should not use list as a parameter name, it conflicts with a built-in procedure of the same name.
  • Don't surround 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.
  • The first error you got stated that you must not define a 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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.