不幸的是,您显示的代码只是为了向您展示本地定义的工作方式。在同一个示例中,您还会看到(define sorted-lst (sort lst ...))
哪个根本不起作用。
这是第 75 页的完整示例代码,其中包含第 74 页的所有部分:
(define (winning-players lst)
(define sorted-lst (sort lst ...)) ;; local variable
(define (winners lst pred) ;; locally defined procedure
(cond
[(empty? lst) (list pred)]
[else
(define fst (first lst))
(if (score> (record-score pred) (record-score fst))
(list pred)
(cons pred (winners (rest lst) fst)))]))
;; START HERE:
;; uses both local variable and the locally defined procedure
(winners (rest sorted-lst) (first sorted-lst)))
他们试图在以下代码中显示的是,在外部winning-players
您无法访问sorted-list
或使用该过程winners
,因为它隐藏在winning-players
' 范围内。
例如。如果您尝试(winners ...)
在球拍交互窗口中使用,您会得到:
获胜者:未定义;不能引用未定义的标识符
如果你明白了,你可以继续享受第 5 章的乐趣 :)
与球拍捆绑在一起,您将拥有来自书下代码的所有代码racket/collects/realm
。有 2 种程序定义,称为winners
. 第一个chapter 10
和第二个chapter 12
。
至于代码做什么的答案。代码中有错误,所以我们需要修复它。我的猜测是 score> 比较了两条记录的分数。我猜它应该是这样的:
(struct record (name score) #:transparent)
(define (winning-players lst)
(define (score> e1 e2) ; defines a new local procedure
(> (record-score e1) ; that compares two records
(record-score e2)))
;; define sorted-list to be lst sorted by score in decreasing order
(define sorted-lst (sort lst score>))
;; procedure winners reduces the list to the elements
;; that have same score as pred
(define (winners lst pred)
(cond
[(empty? lst) (list pred)]
[else
(define fst (first lst))
(if (score> pred fst) ;; changed to work with records
(list pred)
(cons pred (winners (rest lst) fst)))]))
;; START HERE:
;; uses both local variable and the locally defined procedure
(winners (rest sorted-lst) (first sorted-lst)))
(define scores (list (record "John" 10)
(record "Ben" 5)
(record "Mary" 10)
(record "Owen" 2)))
(winning-players scores)
; ==> (list (record "John" 10) (record "Mary" 10))
它返回所有得分最高的列表。