0

I'm having a small issue working with DrRacket. I've programmed pretty extensively in C, C++, Java, Python, etc, but never worked with a functional programming language before so I'm getting tripped up.

I have a node, and I need to return a list of the "eye-color" feature of that node, and all of it's parent elements (and parents' parents etc). Here's what I have, and I can't figure out where I'm going wrong. I suspect it's something to do with all the "empty"s that I'm having to add, because I don't really get those. So many damn parenthesis too, haha. It's getting everything right, but there's a bunch of other space or something instead of one list.

(define (eye-colors f)
  (cond [(empty? f) empty]
        [ else (cons (cons (child-eyes f) (eye-colors (child-mom f))) (eye-colors (child-mom f)))]))

My output for one particular node is this:

(list
 (list
  'blue
  (list 'green (list 'brown))
  (list 'blue))
 (list 'orange))

when it should be this:

(list 'blue 'green 'brown 'blue 'orange)

Any help that you can offer is much appreciated!!

singmotor
  • 3,930
  • 12
  • 45
  • 79
  • This is just a special case of a list-flattening function (albeit using a struct instead of conses as input). There are a number of ways to write a flattening function, including http://stackoverflow.com/a/7324493/13 and http://stackoverflow.com/a/13548087/13. – C. K. Young Oct 18 '14 at 03:46

1 Answers1

0

Got it! The issue was nested lists because of cons. Solved the problem by switching the first cons to an append and everything works great now. The working code is below.

(define (eye-colors f)
  (cond [(empty? f) empty]
        [ else (append (cons (child-eyes f) (eye-colors (child-mom f))) (eye-colors (child-dad f)))]))
singmotor
  • 3,930
  • 12
  • 45
  • 79