Turning list of atoms into a single list using recursion -
i'm looking answer turns list of atoms single list recursively.
an example be, (slist '(a (b c) (d e (f) g) h))
(slist (a b c d e f g h))
any answer helpful.
what you're trying called flattening list. here bunch of options:
; required predicate (define (atom? x) (and (not (null? x)) (not (pair? x)))) ; naïve version using append (define (flatten1 lst) (cond ((null? lst) '()) ((not (pair? lst)) (list lst)) (else (append (flatten1 (car lst)) (flatten1 (cdr lst)))))) ; naïve version using append, map, apply (define (flatten2 lst) (if (atom? lst) (list lst) (apply append (map flatten2 lst)))) ; efficient version using fold-left (define (flatten3 lst) (define (loop lst acc) (if (atom? lst) (cons lst acc) (foldl loop acc lst))) (reverse (loop lst '()))) ; efficient version no higher-order procedures (define (flatten4 lst) (let loop ((lst lst) (acc '())) (cond ((null? lst) acc) ((not (pair? lst)) (cons lst acc)) (else (loop (car lst) (loop (cdr lst) acc))))))
any of above work expected. instance, using flatten4
:
(flatten4 '(a (b c) (d e (f) g) h)) => '(a b c d e f g h)
depending on interpreter you're using, it's quite possible includes implementation. example, in racket:
(flatten '(a (b c) (d e (f) g) h)) => '(a b c d e f g h)
Comments
Post a Comment