I'm trying to sum all integers in a list of structs using a recursive function but cannot for the life of me figure it out.
(struct number (int))
(define ints (list (number 1)
(number 2)
(number 3)))
(define sum (λ (number)
(cond
((null? number) 0) ; Base Case
(#t (+ (number-int (car ints)) ; Take the first of the list
(sum (cdr ints))))))) ; Rest the list
I've spent hours trying different variations of:
(cdr ints), i.e. (number-int (cdr ints)) for the last line
As I believe it's this which is causing the issue (both (cdr ints)
and (number-int (cdr ints))
return something in the form of '(#<number> #<number>)
. But nothing seems to work!
Is there a procedure to returning the cdr of the list in the form of a list of integers rather than '(#<number> #<number>)
?
Any help will be greatly appreciated.
numbers
. then, define eithersum-numbers
function, to be called as(sum-numbers numbers)
, orsum-ints
, to be called as(sum-ints (map number-int numbers))
. the first expectsnumbers
, i.e. a list ofnumber
structs; the second expects a list of ints, so we must transform the list of "number" structs into a list of int numbers, for it (usingmap
). – Will Ness