Combine two lists into one list Racket

我们两清 提交于 2019-12-13 22:19:19

问题


I have a question:

I have two list of numbers for example (list1 3 6 7) and (list2 1 6 4 7). Now I have to combine both into (list3 1 3 4). So 6 and 7 are both in list1 and list2. List3 contains all numbers which occur only once. I hope u get what i mean if not just ask me :s! Here my start:

(define (diff list1 list2)
  (cond
    [(empty? list1) list2] ;; If list1 was empty return directly list2
    [(empty? list2) list1] ;; If list2 was empty return directly list1
    [else
      (???

I know that I have to compare first list1 with every number in list2 and then recursiv again. But how do I programm it?


回答1:


Here's a different, hopefully less-tricky, implementation. (It's O(n), but it requires both of the incoming lists to be sorted; in comparison, Óscar's implementation does not required sorted lists, but it's O(n²).)

(define (diff lhs rhs)
  (let loop ((result '())
             (lhs lhs)
             (rhs rhs))
    (cond ((null? lhs) (append-reverse result rhs))
          ((null? rhs) (append-reverse result lhs))
          (else (let ((a (car lhs))
                      (b (car rhs)))
                  (cond ((< a b) (loop (cons a result) (cdr lhs) rhs))
                        ((< b a) (loop (cons b result) lhs (cdr rhs)))
                        (else (loop result (cdr lhs) (cdr rhs)))))))))

Example:

> (diff '(3 6 7) '(1 4 6 7))
(1 3 4)

append-reverse is from SRFI 1, so in Racket you have to (require srfi/1).



来源:https://stackoverflow.com/questions/28276502/combine-two-lists-into-one-list-racket

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