Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing flatten method in Scheme

Tags:

scheme

I have been working on the following function flatten and so far have it working for just lists. I was wondering if someone could provide me with some insight on how to get it work with pairs? For example (flatten '(a .a)) would return (a a). Thanks.

(define (flatten list)
   (cond ((null? list) null)
         ((list? (car list)) (append (flatten (car list)) (flatten (cdr list))))
         (else
          (cons (car list) (flatten (cdr list))))))
like image 484
user1081812 Avatar asked Dec 17 '22 06:12

user1081812


1 Answers

Here's one option:

(define (flatten x)
  (cond ((null? x) '())
        ((pair? x) (append (flatten (car x)) (flatten (cdr x))))
        (else (list x))))
like image 58
Fred Foo Avatar answered Jan 09 '23 22:01

Fred Foo