I am trying to write a tail-recursive function with an accumulator of joining two sorted lists. input: (40 43 50)(42 46 48) output: (40 42 43 46 48 50)
It needs to be done tail-recursive where we call the accumulator to another function. I am getting stuck in what needs to go in the accumulator function.
(define (rec l1 l2 acc))
(rec (rest l1) l2)
(define (foo l1 l2)
(cond
((null? l1) l2)
((null? l2) l1)
(else
(cond
((<= (car l1) (car l2)) (rec (l2 (cons (first l1) (acc))))
((> (car l1) (car l2)) (rec (l1 (cons (first l2) (acc))))
))))))
You are consing to l1 or l2 and even call the lists as functions, which will not work. In reality you need to cons to the accumulator argument. Here is an example of reverse using tail recursive and accumulator:
You can also keep the helper local:
Your version would need more cases. Eg. base case when
l1andl2are empty. Two cases where eitherl1orl2are empty, and then the last case you cons the lowest of the first element ofl1andl2andcdrthat one for next.. Thus you'll see something like this this if you trace or add breakpoint in the beginning of it:Good luck