实现与递归函数相等的函数 [英] implement equal function to recursion function

查看:71
本文介绍了实现与递归函数相等的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想修复自己的函数,该函数可以使用默认的交集函数得到相同的结果.我一直试图编写一个Lisp代码,在两个列表中打印相同的元素.我的代码为它工作.但是它不适用于嵌套列表.我怎样才能解决这个问题?

I want to fix my own function that gives the same result with the default intersection function. I've been trying to write a lisp code which prints same elements in the two lists. My code works for it. But it doesn't work for nested lists. How can I fix this?

(defun printelems (L1 L2) 
(cond 
((null L1) nil) ((member (first L1) L2) (cons (first L1) (printelems (rest L1) L2)))
(t (printelems (rest L1) L2))))

预期的输入和输出

(printelems '(2 3 5 7) '( 2 3)) => It works
=> (2 3)
(printelems '(a b '(c f)) '(a d '(c f) e)) => It doesn't work.
=> (a (c f))

编辑

使用默认的交集功能可以按预期工作.如何在递归函数中使用equal函数?

Edit

Using the default intersection function works as intended. How can I use the equal function in my recursive function?

对于默认交集,

(intersection '(a b (c f)) '(a d (c f) e) :test 'equal)
((C F) A)
(intersection '(a b (c f)) '(a d c f e) :test 'equal)
(A)

我的路口,

(printelems  '(a b (c f)) '(a d c f e))
(A C F)
(printelems  '(a b (c f)) '(a d (c f) e) )
(A C F)

我编辑的代码:

(defun flatten (l)
  (cond ((null l) nil)
    ((atom (car l)) (cons (car l) (flatten (cdr l))))
    (t (append (flatten (car l)) (flatten (cdr l))))))

(defun printelemsv1(list1 list2)
  (cond
   ((null list1) nil)
   (((member (first list1) list2) (cons (first list1) (printelemsv1 (rest list1) list2)))
   (t (printelemsv1 (rest list1) list2)))))


(defun printelems (L1 L2)
   (printelemsv1 (flatten L1) (flatten L2)))

推荐答案

Common Lisp已经具有 交叉点 功能.如果要比较(C F)之类的子列表,则需要使用等于 equalp 作为测试参数.

Common Lisp already has an intersection function. If you want to compare sublists like (C F), you'll want to use equal or equalp as the test argument.

(intersection '(a b '(c f)) '(a d '(c f) e) :test 'equal)
;=> ('(C F) A)

虽然它不会改变交叉点的工作方式,但您可能真的不希望在列表中使用 quote . 报价不是列表创建操作符;这是一个返回阅读器读取的内容"运算符.读者可以阅读(ab(cf))作为两个符号的列表和一个子列表,因此(quote(ab(cf))),通常缩写为'(ab(cf))很好.例如:

While it doesn't change how intersection works, you probably don't really want quote inside your list. Quote isn't a list creation operator; it's a "return whatever the reader read" operator. The reader can read (a b (c f)) as a list of two symbols and a sublist, so (quote (a b (c f))), usually abbreviated as '(a b (c f)) is fine. E.g.:

(intersection '(a b (c f)) '(a d (c f) e) :test 'equal)
;=> ((C F) A)

这篇关于实现与递归函数相等的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆