I'm stumped on processing this structure, I want to write a function that tells how many topics occur in a discussion.
; a Discussion is (make-discussion String Digressions)
(define-struct discussion [topic digressions])
; Digressions is [ListOf Discussion]
; count-topics : Discussion -> Number
; counts the number of total topics in a discussion, including repeated topics
(define (count-topics d)
(cond
[(empty? (discussion-digressions d)) 0]
[(cons? (discussion-digressions d)) (add1 (count-topics (make-discussion (first (discussion-topic d))
(list (make-discussion (rest (discussion-digressions d)))))))]))
(check-expect (count-topics (make-discussion "music" (list (make-discussion "politics" empty)))) 2)
I've been trying for a few hours and haven't solved it yet. I'm not sure where to go from here, anybody have a sharp eye for Racket? I've tried to process the topic first, but haven't had any luck doing it that way.
You should not use
make-discussionin your solution, we're trying to traverse the structures, not to create new ones. There are two cases to consider:digressionslist is empty, then we've found one topic, and there's nowhere else to go.digressions, adding their results. This is easy to implement usingapplyandmapThis is what I mean:
Of course you can solve this without using
applyandmap, but for that it's better to write separate procedures as Alex suggests. Anyway, my approach works as expected: