Created
November 30, 2011 22:56
-
-
Save ReaperUnreal/1411625 to your computer and use it in GitHub Desktop.
Wrote a flatten function. Witness!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(define (join-list lst1 lst2) #! Wrote my own append just because I could | |
(define (append-item lst item) | |
(if (eq? lst `()) | |
(list item) | |
(cons (car lst) (append-item (cdr lst) item)))) | |
(if (eq? lst2 `()) | |
lst1 | |
(if (list? lst2) | |
(join-list (append-item lst1 (car lst2)) (cdr lst2)) | |
(append-item lst1 lst2)))) | |
(define (flatten slist) | |
(if (eq? slist `()) | |
`() | |
(if (list? (car slist)) | |
(join-list (flatten (car slist)) (flatten (cdr slist))) #! The key here is to use append instead of cons | |
(cons (car slist) (flatten (cdr slist)))))) | |
> (flatten `(a b c)) | |
'(a b c) | |
> (flatten `((a) () (b ()) () (c))) | |
'(a b c) | |
> (flatten `((a b) c (((d)) e))) | |
'(a b c d e) | |
> (flatten `(a b (() (c)))) | |
'(a b c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment