简体   繁体   中英

Keep same list after repeated calls to function in Racket

I'm using Racket and what I want to do is develop a random list of given elements that also has a given length. I know how to create the list but the problem that I'm having is I don't know how to keep the same list every time I call the function using the list from the command line without re-creating the list which would be different since the list is consists of randomly chosen elements. This is what I have:

(define gameColors '(red green blue yellow black))
(define currentGameList '())
(define input 4)
(define randomNumber (random 5))

(if (equal? randomNumber 0)
  (if (< (length currentGameList) (+ input 1))
      (set! currentGameList (append currentGameList (list (car gameColors))))
      ;;otherwise
      (set! currentGameList currentGameList))
  ;;otherwise
  (set! currentGameList currentGameList))

And then the if block repeats for each of the different possible results for randomNumber. All I need to know is how can I call my guess function repeatedly from the command line, which uses currentGameList, without having my program recreate currentGameList every time. The guess function also has parameters that have to be entered by the user so it must be entered at command line each time. Any help is appreciated.

First thing: avoid using set! . In another kind of programming language you'd use mutation of variables for solving the problem, but that's not the way to go in Scheme. The code in the question won't work, nothing on it is iterating or recurring over the color list, and only the first element of gameColors is being picked, every time (there's nothing random about it). If I understood the question (it's a tad confusing), this is what you were aiming for:

(define (generate-random lst len)
  (for/list ([x (in-range len)])
    (list-ref lst (random (length lst)))))

(generate-random '(red green blue yellow black) 4)
=> '(black black blue green) ; one possible output

Of course if you need to save a particular list generated by one invocation of generate-random (because every time the results will be different), simply store the list in a variable for future use:

(define currentGameList (generate-random '(red green blue yellow black) 4))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM