【问题标题】:finding duplicate elemntes in a list with LISP language使用 LISP 语言在列表中查找重复元素
【发布时间】:2015-01-03 17:40:46
【问题描述】:

我是新的 Lisp 程序员,需要一些帮助
我想编写一个在列表中查找重复元素的函数,但我写不出来。
我在 lisp 中需要这样的东西:

for(int i=0; i < myList.length(); i++)  
   for(int j=i+1; j < myList.Length(); j++)
   {  
      if(myList[i] == myList[j])  
         cout << myList[i] << endl;
   }

有人可以帮帮我吗?

【问题讨论】:

  • Stackoverflow 不是让其他人为您将代码从一种语言翻译成另一种语言的地方。希望您表现出努力来解决您的问题,这最好是与编程相关的实际问题。不要发布您尚未尝试找到答案的问题(展示您的作品!)
  • 您的 Algol 代码在列表中找不到重复的元素。例如。对于(1 2 1 1),它打印"1\n1\n1\n2\n1\n1\n1\n"

标签: lisp


【解决方案1】:

如果您有 2 个列表并想在两个列表中查找重复项,为什么不使用 intersection 进行集合交集:

(intersection '(a b c d) '(d f g c)) ;; => (D C)

如果您只关心它的尾巴,那么您可以在第二个列表中添加cdr

(intersection '(a b c d) (cdr '(d f g c))) ;; => (C)

【讨论】:

    【解决方案2】:

    给这只猫剥皮的几种方法,这是一种方法,

    (defun dupes (lst)
      (cond ((null lst) '())
            ((member (car lst) (cdr lst)) (cons (car lst) (dupes (cdr lst))))
            (t (dupes (cdr lst)))))
    

    请注意,最好使用LOOP 宏直接翻译您的原始代码。但以上对你来说是一个开始。

    【讨论】:

      【解决方案3】:

      如果你使用方案语言,你可以用尾递归构造函数。示例:

      ;; this function collect list items, which
      ;; included into input-list more than once
      (define (duplicates input-list)
        ;; declare nested core function
        (define (core lst acc)
          ;; cond is like c++ expression:
          ;; if () ...
          ;; else if () ...
          ;; ...
          ;; else ...
          (cond ((null? lst)
                 ;; if list is empty, return accumulator
                 acc)
                ((member (car lst) (cdr lst))
                 ;; if head of list will exist in tail of list
                 ;; call new iteration with accumulate head of list
                 ;; and remove it from the tail
                 (core (remove* (list (car lst)) lst) (cons (car lst) acc)))
                ;; else new iteration with tail of list
                (else
                 (core (cdr lst) acc))))
        ;; now we call core function
        (core input-list '()))
      

      方案编译器(或解释器)会将尾调用优化为循环。如果您使用 common lisp 编写,您的实现很可能具有 TCO(尾调用优化),并且此代码可能比“recursion with return”更快:

      ;;; function return list of duplicates
      ;;; &optional keyword say's that 'argument by default'
      (defun duplicates (lst &optional acc)
        (cond ((null lst)
                acc)
              ((member (car lst) (cdr lst))
               (duplicates (remove (car lst) lst) (cons (car lst) acc)))
              (t
               (duplicates (cdr lst) acc))))
      

      这是用不同的 lisp 语言编写的相同函数。

      【讨论】:

        猜你喜欢
        • 2010-10-10
        • 2016-06-28
        • 2014-04-21
        • 2015-08-08
        • 2021-01-01
        • 2014-01-08
        • 1970-01-01
        • 2016-01-11
        • 2019-02-21
        相关资源
        最近更新 更多