0

I have just started learning scheme, and I find the cons-cdr part a bit hard to understand. I am making a function which takes a list, then displays all the atoms in that list, including in the sub lists as if it were one big list. It would look like this: (flatten '(1 (2 3) 4 5 (6 7)))

(1 2 3 4 5 6 7)

Here is my code:

(define (flatten list1)
    (if (not (empty? list1))
     (if (atom? (car list1))
     (cons (car list1)(flatten (cdr list1)))
     (begin
     (flatten (car list1))
     (flatten (cdr list1))))
     '()))

However, when doing this, it removes the sublists. So (flatten '((1 2) 3 4) would give (3 4) instead of (1 2 3 4).

Any help? The problem is probably in the "(begin" section, but i can't figure it out..

Thanks!

Renzo
  • 26,848
  • 5
  • 49
  • 61
P. Rick
  • 3
  • 4
  • Is this a homework assignment, or are you just trying to understand on your own? My hint (if this is homework) is that the entire list you've provided is getting processed, but you are never combining the output of the two functions in your `begin` section. This means that only `(flatten (cdr list1))` is actually getting returned. – Ben I. Oct 24 '16 at 12:43
  • Also, do you need to be able to go arbitrarily deep into lists, or is a depth of 1 sufficient? By which I mean should `((1 2) 3 ((4 5) 6))` process to `(1 2 3 (4 5) 6)` or `(1 2 3 4 5 6)`? – Ben I. Oct 24 '16 at 12:46

1 Answers1

0

try something like this in your your begin block

(append (flatten (car aList)) (flatten (cdr aList)))

Also the post it's almost the same question if not the same: flatten list

Community
  • 1
  • 1
Joe Doe
  • 141
  • 1
  • 3