Scheme merge two lists into one

╄→гoц情女王★ 提交于 2019-12-14 03:53:19

问题


how to design a function that merge two lists into one list. the first element of first list will be the first element of the new list and the first element of the second list will be the second element of the new list (a,b,c,d,e,f) (g,h,i) will be (a,g,b,h,c,i,d,e,f,)


回答1:


The procedure you're trying to implement is known as interleave or merge. Because this looks like homework, I can't leave you a straight answer, instead I'll point you in the right direction; fill-in the blanks:

(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.



回答2:


Here is a purely functional and recursive implementation in R6RS

(define (merge l1 l2)
      (if (null? l1) l2
          (if (null? l2) l1
              (cons (car l1) (cons (car l2) (merge (cdr l1) (cdr l2)))))))



回答3:


There is no need to check both lists: Here is a simple version:

    (define (interleave lx lz)
  (cond
    [(empty? lx) lz]
    [else (cons (first lx)(interleave lz (rest lx)))]))


(check-expect(interleave '() '())'())
(check-expect(interleave '(X X X X X X) '(O O O O O))
             (list 'X 'O 'X 'O 'X 'O 'X 'O 'X 'O 'X))
(check-expect(interleave '(1 2 3) '(a b c d e f))
             (list 1 'a 2 'b 3 'c 'd 'e 'f))


来源:https://stackoverflow.com/questions/12646888/scheme-merge-two-lists-into-one

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