Reputation: 623
For reference I am programming in Scheme
using DrRacket
.
I am trying to count the number of times a name (string) is the first choice in a list of votes, but cannot seem to figure it out.
For some context of the problem,
A vote consists of the names of the three candidates that one person has voted for. This is defined as the structure: (define-struct vote (choice1 choice2 choice3)).
The function top-votes-for is supposed to consume 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.
This is my code (note the definition is incorrect):
;; 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)))]
)
)
Thank you in advance!
Upvotes: 0
Views: 93
Reputation: 223203
Your definition of top-votes-for
is wrong. Here's a skeletal version of a corrected solution:
(define (top-votes-for cand alov)
(cond ((empty? alov) 0)
((string=? (vote-choice1 <???>) cand)
(add1 <???>))
(else (top-votes-for cand (rest alov)))))
I've actually given you most of a solution. The rest of it should be easy to figure out, if you understand the code above.
Upvotes: 1