Nikolai Naidenov
Nikolai Naidenov

Reputation: 37

Combine two lists of 3 characters into 3 pairs

I'm having a little trouble with this. Basically, I need a procedure comb that takes two lists (comb '(a b c) '(1 2 3) and returns ('a 1)('b 2)('c 3). I came up with a part of the cod which returns the first pair

(define some-letters '(a b c))
(define some-nums '(1 2 3))
(define x (first (foldr cons empty some-letters)))
(define y (first (foldr cons empty some-nums)))
(define (comb list1 list2)
  (cond
   [(empty? list1) empty]
   [(empty? list2) empty]
    [else (list x y)]))

Now, I tinkered around a little bit longer and came up with defining comb a bit differently:

(define (comb list1 list2)
  (cond
   [(empty? list1) empty]
   [(empty? list2) empty]
    [else ((list x y) (zip (rest list1) (rest list2)))]))

but this returns the following:

function call: expected a function after the open parenthesis, but received (list 'a 1)

I would appreciate any assistance you can provide.

Upvotes: 0

Views: 1142

Answers (2)

Farticustheelder
Farticustheelder

Reputation: 1

Try this:

(defvar lst1 '(a b c d e f))

(defvar lst2 '(1 2 3 4 5))

Note that the lists are of different length.

(defun 2list (x y)

(list x y))

Note 2list is a function of two arguments that combines them into a list

(defun comb (lstA lstB)

(mapcar #'2list lstA lstB))

This should return ((A 1) (B 2) (C 3) (D 4) (E 5))

mapcar stops when the end of the shortest list is reached, the function 2list is the type of thing anonymous functions (lambdas) are good for, unless you plan on using it in several places.

Upvotes: 0

Óscar López
Óscar López

Reputation: 235994

There are two problems with your implementation:

  • You forgot to cons the current element in the output list that's being built
  • You named the function comb, not zip (although this function is usually known as zip), therefore comb must be used when performing the recursive call

This fixes the problems:

(define (comb list1 list2)
  (cond
    [(empty? list1) empty]
    [(empty? list2) empty]
    [else (cons (list (first list1) (first list2))
                (comb (rest list1) (rest list2)))]))

Or try this for an even simpler implementation, with the caveat that only works for lists with the same length:

(define (comb list1 list2)
  (map list list1 list2))

Upvotes: 2

Related Questions