The goal is to remove all inner brackets.
(flatten '(a (bc) d)) becomes' (abcd)
This is my Racket code.
; if slist is null, return empty
; otherwise, if it is a pair, recursively solve car and cdr and concat them
; if it is a symbol, return the symbol
(define flatten
(lambda (slist)
(cond
[ (null? slist) '()]
[ (pair? slist)
(cons ((flatten (car slist)) (flatten (cdr slist))))]
[ (symbol? slist) slist])))
He complains
procedure application: expected procedure, given: c; arguments were: ()
which means that I'm trying to access carand cdrfor an empty list.
I did the trace:
> (flatten '(a (b c) d))
pair?-car-cdr
a
((b c) d)
symbol?
a
pair?-car-cdr
(b c)
(d)
pair?-car-cdr
b
(c)
symbol?
b
pair?-car-cdr
c
()
symbol?
c
(stops here)
The trace code is simple - a bunch of displays.
(define flatten
(lambda (slist)
(cond
[ (null? slist) '()]
[ (pair? slist)
(display 'pair?-car-cdr)
(newline)
(display (car slist))
(newline)
(display (cdr slist))
(newline)
(cons ((flatten (car slist)) (flatten (cdr slist))))]
[ (symbol? slist)
(display 'symbol?)
(newline)
(display slist)
(newline)
slist])))
I do not understand why the first condition (null? slist)did not catch an empty list? I have two recursive calls. If he caught an empty list, he will move on to the next recursion, which is a list {d}.
What is the problem with my recursion logic?
Update version
(define flatten
(lambda (slist)
(cond
[ (null? slist) '()]
[ (pair? slist)
(cons (flatten (car slist)) (flatten (cdr slist)))]
[ (symbol? slist) slist])))
(display (equal? (flatten '(a (b a) b a c (a b) c (e f (b a)))) '(a b a b a c a b c e f b a)))
(newline)
(display (equal? (flatten '(a b c)) '(a b c)))
(newline)
(display (equal? (flatten '(a (b c))) '(a b c)))
(newline)
(display (equal? (flatten '((a)(b)(c) d)) '(a b c d)))
(newline)
(display (equal? (flatten '(a (b) ((c)) (((d))) ((((e (f g))))))) '(a b c d e f g )))
(newline)
(display (equal? (flatten '()) '()))
(newline)
(display (equal? (flatten '(a b () ())) '(a b)))
(newline)
, , . , , , (2- )
-, (cons (flatten slist) empty)