Vladi
Vladi

Reputation: 2010

I need to merge two lists in Scheme, taking one element from each one

This is what I've written:

(: mmm : (Listof Any) (Listof Any) -> (Listof Any))
(define (mmm list1 list2)
  (cond [(or (null? list1) (null? list2)) null]
        (and (cons (first list1) (first list2)) (mmm (rest list1) (rest list2)))))

I'll give you an example:

list1:  a b c
list2:  1 2 3
answer: ((a 1) (b 2) (c 3))

edited they both same size

Upvotes: 0

Views: 1792

Answers (3)

R Sahu
R Sahu

Reputation: 206747

If you are allowed to use map, you can use:

(define (mmm lst1 lst2) (map (lambda (x y) (list x y)) lst1 lst2))

Upvotes: 2

GoZoner
GoZoner

Reputation: 70275

If you know the lists are the same size, then it becomes simply:

(define (mmm list1 list2) (map list list1 list2))

Note: Replace map list with map cons if that is what you really want. Your code used cons but your result example suggests that list is what you want.

Upvotes: 1

Óscar López
Óscar López

Reputation: 236170

There are a couple of problems with your code:

  • The base case might or might not be right - if the input lists are guaranteed to be of the same size, then it's fine. If they can be of different size see @Sylwester's answer for advice
  • The second condition should start with an else (because it's the last one and the conditions are mutually exclusive), not with and
  • You are not building the output list correctly. The new element to be added is a list with the first element of both input lists, and that must be consed to the result of calling the recursion

To fix them, try this - assuming input lists of equal length:

(define (mmm list1 list2)
  (cond [(or (null? list1) (null? list2)) null]
        [else (cons (list (first list1) (first list2))
                    (mmm (rest list1) (rest list2)))]))

Now the procedure works as expected:

(mmm '(a b c ) '(1 2 3))
=> '((a 1) (b 2) (c 3))

Upvotes: 1

Related Questions