0
仅供参考我正在编程Scheme
使用DrRacket
。计数项目出现在结构化列表中的方案
我想计算一个名称(字符串)是选票列表中的第一选择的次数,但似乎无法弄清楚。
对于这个问题的一些背景,
进行投票表决由三个候选人的名字,一个人投票支持的。这被定义为结构:(define-struct vote(choice1 choice2 choice3))。
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)))]
)
)
预先感谢您!
我会认为“cand”和“alov”会适合那些?部分(按顺序),但似乎并非如此... @chrisj – BBladem83 2014-11-25 13:06:25
认为更难。提示:这些“??>”中的每一个都是一个完整的表达式,而不仅仅是一个变量。第一个形状为'(??>??>)',第二个形状为'(??>??>(??>??>))''。 – 2014-11-25 13:50:38
嗯。第一个??>肯定是'(vote-choice1(first alov))cand)'我想,但我不太确定第二个??>。也许符合'(add1 top-votes-for(rest alov))'的意思? @Chris @ChrisJester @ ChrisJester-Young – BBladem83 2014-11-25 15:46:57