用LISP语言查找列表中的重复元素

用LISP语言查找列表中的重复元素,lisp,Lisp,我是新的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; }

我是新的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;
   }
for(int i=0;i有几种方法可以剥这只猫的皮,这里有一种方法

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

请注意,最好使用
循环
宏编写原始代码的直接翻译。但以上是一个开始。

如果使用scheme语言,则可以使用尾部递归构造函数。示例:

;; 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 '()))
scheme编译器(或解释器)将以循环方式优化尾部调用。如果您在common lisp上编写,您的实现很可能具有TCO(尾部调用优化),并且此代码可能比“带返回的递归”更快:

;;; 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语言编写的相同函数。

如果您有两个列表,并且希望在这两个列表中找到重复的函数,为什么不使用
交叉点
来设置交叉点:

(intersection '(a b c d) '(d f g c)) ;; => (D C)
如果您只关心它的尾部,则可以在第二个列表上执行
cdr

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

Stackoverflow不是一个让其他人将代码从一种语言翻译成另一种语言的地方。你应该努力解决你的问题,这最好是一个与编程相关的实际问题。不要发布你没有试图找到答案的问题(展示你的工作!)您的Algol代码在列表中找不到重复的元素。例如,对于
(1 2 1)
,它打印
“1\n1\n1\n2\n1\n1\n”