Scheme将两个列表合并为一个

Joh*_*ohn 3 scheme

如何设计将两个列表合并为一个列表的函数.第一个列表的第一个元素将是新列表的第一个元素,第二个列表的第一个元素将是新列表的第二个元素(a,b,c,d,e,f)(g,h, i)将是(a,g,b,h,c,i,d,e,f,)

Asl*_*986 13

这是一个纯粹的功能和递归实现 R6RS

(define (merge l1 l2)
      (if (null? l1) l2
          (if (null? l2) l1
              (cons (car l1) (cons (car l2) (merge (cdr l1) (cdr l2)))))))
Run Code Online (Sandbox Code Playgroud)


Ósc*_*pez 6

您尝试实施的程序称为interleavemerge.因为这看起来像家庭作业,我不能给你一个直接的答案,而是我会指出你正确的方向; 填空:

(define (interleave lst1 lst2)
  (cond ((null? lst1)     ; If the first list is empty
         <???>)           ; ... return the second list.
        ((null? lst2)     ; If the second list is empty
         <???>)           ; ... return the first list.
        (else             ; If both lists are non-empty
         (cons (car lst1) ; ... cons the first element of the first list
               <???>))))  ; ... make a recursively call, advancing over the first
                          ; ... list, inverting the order used to pass the lists.
Run Code Online (Sandbox Code Playgroud)