Reputation: 3579
Given a structure layer
defined:
(define-struct layer [color doll])
I am trying to write a function that will produce a string of colors of all the dolls.
; colors: Russian doll (RD) -> String
; consumes an RD and produces a string of all colors
(define (colors an-rd)
(cond
[(string? an-rd) (string-append an-rd ",")]
[else
(colors (layer-doll an-rd))]))
(colors
(make-layer
"yellow"
(make-layer
"green" "red")))
I would like for colors
function, given the above input, to produce yellow, green, red
; however, it only returns red
. What am I doing wrong here?
Upvotes: 0
Views: 216
Reputation: 236004
The base case is in correct (it should simply return a string), and consequently the call to string-append
is in the wrong place; the idea is to append a piece of the string at each recursive call until there are no more pieces. Try this instead:
(define (colors an-rd)
(cond
[(string? an-rd) an-rd]
[else
(string-append (layer-color an-rd)
", "
(colors (layer-doll an-rd)))]))
For example:
(colors
(make-layer
"yellow"
(make-layer
"green" "red")))
=> "yellow, green, red"
Upvotes: 2