Combine two lists of 3 characters into 3 pairs

 ̄綄美尐妖づ 提交于 2020-01-07 07:48:09

问题


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.


回答1:


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))



回答2:


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.



来源:https://stackoverflow.com/questions/19919838/combine-two-lists-of-3-characters-into-3-pairs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!