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