user2786737
user2786737

Reputation: 55

Merge two "list in list" in scheme

I don't know how to exactly express my question in language. Pardon my ambiguous words in the title

My question is:

If you have

a = [[1, 2], [3, 4], [5, 6]....], b = [[1, 3], [4, 8], ....]

How to merge a and b like

[[1,2], [3, 4], [5, 6], [1, 3], [4, 8]....]

in scheme??

I have already tried using car or write a function my self to solve it, but all failed. I was thinking to use (cons a b), but it'll give me [[[1, 2], [3, 4]...], [[1, 3], [4, 8]...]] which is not what I want. I tried to write a recursive function, but still I'll get the similar trouble as (cons a b)

Thanks!

Upvotes: 1

Views: 1446

Answers (1)

Óscar López
Óscar López

Reputation: 236004

As pointed out in the comments, you're looking for append. This is how the code in the question would look like in Scheme:

(define a '((1 2) (3 4) (5 6)))
(define b '((1 3) (4 8)))

(append a b)
=> '((1 2) (3 4) (5 6) (1 3) (4 8))

If you want to implement your own version of append it's simple enough:

(define (my-append lst1 lst2)
  (if (null? lst1)
      lst2
      (cons (car lst1)
            (my-append (cdr lst1) lst2))))

(my-append a b)
=> '((1 2) (3 4) (5 6) (1 3) (4 8))

Upvotes: 2

Related Questions