Reputation: 71
Say you want append these list of lists and output a single list that contains all the numbers
(append-lists (list (list 1 2)
(list 4 5)
(list 10 19))) => (list 1 2 4 5 10 19)
If using trivial append, i can do this,
((define (append-lists llon)
(cond
[(empty? llon) empty]
[(cons? llon) (cons (first llon)
(append-lists (rest llon)))]))
But how to get the same output without using append just by recursion?
Upvotes: 0
Views: 464
Reputation: 18937
This is a special case of flattening. Some Scheme implementation feature a build-in flatten
procedure; if not, a general flattening algorithm is :
(define (flatten sxp)
(let loop ((sxp sxp) (res '()))
(cond
((null? sxp) res)
((pair? sxp) (loop (car sxp) (loop (cdr sxp) res)))
(else (cons sxp res)))))
Testing:
> (flatten (list (list 1 2) (list 4 5) (list 10 19)))
'(1 2 4 5 10 19)
> (flatten (list (list 1 2) 'a (list 4 5) 'b (list 10 19)))
'(1 2 a 4 5 b 10 19)
Upvotes: 2