Remove duplication from the Scheme function

南楼画角 提交于 2019-12-11 18:37:45

问题


(define (merge-sorted lst1 lst2)
  (cond ((null? lst1) lst2)
        ((null? lst2) lst1)
        ((>= (car lst1) (car lst2))
         (cons (car lst2) (merge-sorted lst1 (cdr lst2))))
        (else
         (cons (car lst1) (merge-sorted (cdr lst1) lst2)))))
Output:

(merge-sorted '(1 3 4) '(2 4 5))
=> '(1 2 3 4 4 5)

I have to write function on lists in Scheme. How can I fix the duplication?


回答1:


Instead of having >= as one condition, you can test equality separately, whereby whenever (car lst1) is equal to (car lst2), you would keep one of them, but remove both on your recursive call by doing:

(cons (car lst1)
      (merge-sorted (cdr lst1) (cdr lst2)))

For example:

(define (merge-sorted lst1 lst2)
  (cond
    ((null? lst1) lst2)
    ((null? lst2) lst1)
    ((> (car lst1)
        (car lst2))
     (cons (car lst2)
           (merge-sorted lst1 (cdr lst2))))
    ((< (car lst1)
        (car lst2))
     (cons (car lst1)
           (merge-sorted (cdr lst1) lst2)))
    (else
     (cons (car lst1)
           (merge-sorted (cdr lst1) (cdr lst2))))))

then you would have:

(merge-sorted '(1 3 4) '(2 4 5))
=> '(1 2 3 4 5)


来源:https://stackoverflow.com/questions/47447875/remove-duplication-from-the-scheme-function

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