Lisp关联列表错误 [英] Lisp association list error

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

问题描述

我编写了将cons单元插入关联列表的代码. 例如,有关联列表

I write the code that insert cons cell into association list. For example, there is association list

((1 . a) (3 . c) (4 . d))

我想插入cons单元格(2 . b),然后该程序生成

and I want to insert cons cell (2 . b) then this program produces

((1  a) (2 . b) (3 . c) (4 . d))

但是我的代码引发了异常

but my code raises an exception

(car L) should be a lambda expression

下面是我的代码

(defun INSERTCELL (R L)
  (cond ((< (car L) (car R)) cons((car L) INSERTCELL(R (cdr L))))
        (t cons(R L))))

R(2 . b)L((1 . a) (3 . c) (4 . d)),因此应将R插入L.

R is (2 . b), and L is ((1 . a) (3 . c) (4 . d)) so R should be inserted into L.

推荐答案

Lisp中的函数调用是缺点单元格:

Function calls in Lisp are cons cells:

(cons 1 2)
==> (1 . 2)

如果您修改了代码,则

(defun insertcell (R L)
  (cond ((< (caar L) (car R)) (cons (car L) (insertcell R (cdr L))))
        (t (cons R L))))

有效:

(insertcell '(2 . b) '((1 . a) (3 . c) (4 . d)))
==> ((1 . A) (2 . B) (3 . C) (4 . D))

请注意,您还需要执行(caar L),而不是(car L),因为L是一个列表,因此要访问第一个密钥,您需要调用两次car.

Note that you also need to do (caar L), not (car L) because L is an alist, so to access the first key you need to call car twice.

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

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