Racket:将名称绑定到索引是什么意思?

时间:2017-04-29 20:21:11

标签: user-interface button racket

我正在编写用户从选项列表中选择的代码。我在下面定义了我的列表:

;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"))

我的按钮从以下代码的列表中获取名称(仅显示一个示例)。在这种情况下,它从列表中获取第三项:

[label (list-ref choices 2)]

当我想更改名称时,我会使用代码行:

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

我的教授评论说我应该将名字绑定到6 7等,这样你的代码就是可读的。我仍然对他的意思以及我将如何这样做感到困惑。

2 个答案:

答案 0 :(得分:1)

他指的是每个索引,定义一个绑定到该索引的标识符,理想情况下以它的含义命名,例如:

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

所以现在你可以写[label (list-ref choices choice3)]而不是[label (list-ref choices 2)]。代码更具可读性,并且在必要时更容易更改,因为您可以更改标识符的绑定,而不是代码中出现数字的每个位置。

顺便说一下,你现在正在做的是使用"魔术数字。"

答案 1 :(得分:1)

之前的答案很好,我已经赞成了。我只想提一下,像这样的通用数据结构是一个关联列表,您可以将符号或数字之类的内容与值相关联,然后使用assqassv进行查找,或assoc,具体取决于您的查询名称是否分别需要eq?eqv?equal?。考虑一下:

(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!"
>