Racket/Scheme中的zip功能

use*_*726 8 lisp recursion scheme functional-programming racket

给定两个列表,返回一个列表,其元素是大小为2的列表,这样对于i-th列表,第一个元素是i第一个原始列表的i第 - 个元素,第二个元素是第二个原始列表的第 - 个元素名单.如果一个列表小于另一个列表,则结果列表的大小最小; 因此,如果其中一个列表为空,则返回一个空列表.例如:

> (zip '(1 2) '(3 4))
'((1 3) (2 4))

> (zip '(1 2 3) '())
'()
> (zip '() '(4 5 6))
'()
> (zip '(8 9) '(3 2 1 4))
'((8 3) (9 2))
> (zip '(8 9 1 2) '(3 4))
'((8 3) (9 4))
Run Code Online (Sandbox Code Playgroud)

ali*_*oar 10

试试这样:

(map cons '(1 2 3) '(a b c))
Run Code Online (Sandbox Code Playgroud)

或者:

(map list '(1 2 3) '(a b c))
Run Code Online (Sandbox Code Playgroud)
(define zip (lambda (l1 l2) (map list l1 l2)))

->(zip '(1 2 3) '(x y z))
'((1 x) (2 y) (3 z))
Run Code Online (Sandbox Code Playgroud)

  • `(map cons'(1 2 3)'(abc)); ==>((1.a)(2.b)(3.c))`,而不是期望的结果`(((1 a)(2 b)(3 c))) (2认同)

Ósc*_*pez 4

因为您没有发布您编写的代码,所以我猜这是作业。我会给你一些开始的提示,这是解决方案的一般结构,填空 - 如果你自己找到正确的答案,会更有趣!

(define (zip lst1 lst2)
  (cond ((<???> lst1)  ; if the first list is empty
         <???>)        ; then return the empty list 
        ((<???> lst2)  ; if the second list is empty
         <???>)        ; then also return the empty list 
        (else          ; otherwise
         (cons (list   ; cons a list with two elements:
                <???>  ; the first from the first list
                <???>) ; and the first from the second list
               (zip <???> <???>))))) ; advance recursion over both lists
Run Code Online (Sandbox Code Playgroud)

我使用示例输入测试了上述实现,结果符合预期:

(zip '(1 2) '(3 4))
=> '((1 3) (2 4))

(zip '(1 2 3) '())
=> '()

(zip '() '(4 5 6))
=> '()

(zip '(8 9) '(3 2 1 4))
=> '((8 3) (9 2))

(zip '(8 9 1 2) '(3 4))
=> '((8 3) (9 4))
Run Code Online (Sandbox Code Playgroud)