Brogrammer
Brogrammer

Reputation: 311

Racket: What does it mean to bind names to the index?

I'm writing code where the user picks from a list of choices. I have defined my list in the following:

;contains the options the user can pick
(define choices (list "choice1" "choice2" "choice3" "choice4" "choice5" "choice6" "OPENING VALUE" "HIGHEST VALUE" "LOWEST VALUE" "CLOSING VALUE" "VOLUME OF SHARES" "ADJUSTED CLOSING VALUE"))

My button gets the name from the list from the following code(only showing one example). In this case it takes the third item from the list:

[label (list-ref choices 2)]

and when I want to change the name then I use the line of code:

(send choice-4-9 set-label (list-ref choices 9))

My prof commented that I should bind names to 6 7 etc so your code would be readable. I'm still a little confused on what he meant by that and how I would do so.

Upvotes: 1

Views: 56

Answers (2)

law-of-fives
law-of-fives

Reputation: 643

The previous answer is good and I have upvoted it. I only want to mention that a common data structure for something like this is an association list, where you associate something like a symbol or number to a value, and then look it up using assq, assv, or assoc depending on the whether your lookup name requires eq?, eqv?, or equal? respectively. Consider:

(define choices
  '((shoot . "Shoot!")
    (run . "Run away!")
    (reload . "Reload")
    (appraise . "Search your surroundings")))

(define (get-label choice)
  (let ((result (assq choice choices)))
    (if (not result)
        (error "???") ; handle as you see fit
        (cdr result))))

;;;;;;;;;;;;;;;;
Welcome to DrRacket, version 6.4 [3m].
Language: racket/base [custom]; memory limit: 8192 MB.
> (get-label 'shoot)
"Shoot!"
> 

Upvotes: 1

Brendan Cannell
Brendan Cannell

Reputation: 679

He means for each index, define an identifier bound to that index, ideally named after what it means, e.g.:

(define choice1 0)
(define choice2 1)
(define choice3 2)
....

So now you can write [label (list-ref choices choice3)] instead of [label (list-ref choices 2)]. The code is more readable, and easier to change if necessary because you can change the binding of the identifier rather than every place where the number appears in code.

Incidentally, what you're doing now is called using "magic numbers."

Upvotes: 1

Related Questions