作为参考,我正在使用DrRacket
在Scheme
中编程。
我试图计算名称(字符串)是投票列表中第一选择的次数,但似乎无法弄清楚。
对于问题的某些上下文,
投票由一个人投票支持的三名候选人的姓名组成。这被定义为结构:(定义结构投票(选择1选择2选择3))。
top-votes-for 函数应该使用名称和投票列表,并生成给定名称是投票列表中第一选择投票的次数。
这是我的代码(注意定义不正确):
;; Data Definition
(define-struct vote (choice1 choice2 choice3))
;; A vote is a structure: (make-vote String Number String).
;; interp. 3 candidates that one person has voted for (String)
(define vote1
(make-vote "Blake" "Joey" "Will"))
(define vote2
(make-vote "Blake" "Bob" "Ash"))
(define vote3
(make-vote "Bob" "Ash" "Blake"))
(define listofVotes
(list vote1 vote2 vote3))
;; Signature: top-votes-for: string list-of-strings -> number
;; Purpose: Consumes a name and a list of votes and produces the number of
;; times that the given name was the first choice vote in the list of votes.
;; Tests:
(check-expect (top-votes-for "Blake" empty) 0)
(check-expect (top-votes-for "Blake" listofVotes) 2)
(check-expect (top-votes-for "Bob" listofVotes) 1)
(check-expect (top-votes-for "Ash" listofVotes) 0)
;; Define:
(define (top-votes-for cand alov)
(cond
[(empty? alov) 0]
[(string=? (vote-choice1 cand) cand) 1]
[else ((first alov) (top-votes-for (rest alov)))]
)
)
提前谢谢你!
你对top-votes-for
的定义是错误的。下面是更正解决方案的框架版本:
(define (top-votes-for cand alov)
(cond ((empty? alov) 0)
((string=? (vote-choice1 <???>) cand)
(add1 <???>))
(else (top-votes-for cand (rest alov)))))
我实际上已经给了你大部分的解决方案。如果您理解上面的代码,其余部分应该很容易弄清楚。