Skip to content

Instantly share code, notes, and snippets.

@ReaperUnreal
Created November 30, 2011 22:56
Show Gist options
  • Save ReaperUnreal/1411625 to your computer and use it in GitHub Desktop.
Save ReaperUnreal/1411625 to your computer and use it in GitHub Desktop.
Wrote a flatten function. Witness!
(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