Lisp联合功能 [英] Lisp union function

查看:80
本文介绍了Lisp联合功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不介意承认这是我的一项家庭作业.向正确方向的任何推动都是有用的.

I don't mind admitting that this is a homework task that has me stumped. Any push in the right direction would be useful.

我需要编写一个函数,该函数返回两个给定列表的并集.我相信我的逻辑是正确的,但是Lisp语法使我望而却步.

I'm required to write a function that returns the union of the two given lists. I believe my logic is sound, but Lisp syntax is driving me up a wall.

到目前为止,我的解决方案是这个.

My solution so far is this.

(defun inList (e L)
  (cond 
   ((null L) 
    nil) 
   ((equal (first L) e) 
    T) 
   (T 
    (inList e (rest L)))))

(defun union2 (L1 L2)
  (cond 
   ((null L2) 
    L1) 
   ((not (inList (first L2) L1)) 
    (append (union2 L1 (rest L2)) (first L2))) 
   (T 
    (union2 L1 (rest L2)))))

当我用一个空列表作为第二个参数或第二个参数是一个列表(其中每个项目都是第一个列表的成员)的功能时,它正常工作.

When I test the function with an empty list as the second argument, or with the second argument being a list in which every item is a member of the first list, it works correctly.

但是,当与 (union2 '(1 2 3) '(4 5 6))我得到6 is not of type list.

我相当确定我的错误出在:(append (union2 L1 (rest L2)) (first L2)

I'm fairly certain that my error is in: (append (union2 L1 (rest L2)) (first L2)

到那时,(first L2)显然不是列表.但是,将其写为((first L2))会给我Badly formed lambda.

As at that point, (first L2) is obviously not a list. However, writing it as ((first L2)) is giving me Badly formed lambda.

正如我所说,任何提示或指示都将不胜感激.

As I said, any tips or pointers would be appreciated.

推荐答案

您确实需要缩进代码.大多数Lisp用户都可以理解以下内容.它会自动正确缩进,并且在自己的行上没有括号.

You really need to indent your code. The following is understood by most Lisp users. It is automatically and properly indented and has no parentheses on their own lines.

(defun union2 (L1 L2)
  (cond 
   ((null L2) L1)
   ((not (inList (first L2) L1)) 
    (append (union2 L1 (rest L2))
            (first L2))) 
   (T (union2 L1 (rest L2)))))

所以您认为(append ... (first L2))有问题吗?

append期望列表作为参数. l2的第一个元素可能不是列表.

append expects lists as arguments. The first element of l2 probably is not a list.

您如何列出清单?

  • (append l1 l2 ...)返回附加列表的列表
  • (cons item l1)返回将item添加到l1前面的列表.
  • (list e1 ...)返回以元素e1 ...作为元素的列表.它需要零个或多个参数.
  • (append l1 l2 ...) returns a list of the appended lists
  • (cons item l1) returns a list with the item added to the front of l1.
  • (list e1 ...) returns a list with the items e1 ... as elements. It takes zero or more arguments.

以上其中一项应该可以帮助您从项目中创建新列表.

One of the above should help you to create a new list from an item.

还请注意,在Lisp中,追加到列表末尾并不是有效的列表操作.最好将元素添加到列表的开头.

Also note that appending to the end of a list is not an efficient list operation in Lisp. Adding elements to the front of a list is preferred.

这篇关于Lisp联合功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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