函数中删除重复项

函数中删除重复项

本文介绍了从 Scheme 函数中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我必须在 Scheme 中的列表上编写函数.我该如何解决重复问题?

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

推荐答案

代替 >= 作为一个条件,您可以单独测试相等性,即每当 (car lst1) 等于 (car lst2),您将保留其中之一,但通过执行以下操作在递归调用中删除两者:

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)))

例如:

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

那么你会:

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

这篇关于从 Scheme 函数中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 08:23