gpt4 book ai didi

list - 我定义的 cond 函数无法正常工作 (LISP)

转载 作者:太空宇宙 更新时间:2023-11-03 18:56:21 25 4
gpt4 key购买 nike

我正在尝试定义我自己的函数以使我的 hw2 更容易,但它不起作用。你能看一下它并告诉我我缺少什么吗?

    (DEFUN testAL(x)
COND ( ( ATOMP(x) ) 'this-is-an-atom )
( ( LISTP(x) ) 'this-is-a-list )
( T 'this-is-neither ) )

我希望这个条件函数接受输入 X 并输出它是原子、列表还是两者都不是。问题是,当我输入 NIL 时,出现错误:Attempt to take the value of the unbound variable `COND'。

家庭作业 2 包含以下问题:

Which of the following are atoms, which lists, which both and witch neither?

a. nil

b. (expt 10 3)

c. (a b)

d. 64

e. T

f. (No place like home)

g. ‘(+ 3 5 6)

最佳答案

您的括号不在正确的位置。除非引用,否则括号是函数应用程序的开始。

它以未绑定(bind)的变量 cond 开头。它不是特殊形式 (cond (predicate consequent) (predicate2 consequent2)) 因为它不是以左括号开头。

仅从缩进来看,我猜你打算写:

(DEFUN testAL (x)
(COND ((ATOM x) 'this-is-an-atom)
((LISTP x) 'this-is-a-list)
(T 'this-is-neither)))

(testal 'test) ; ==> THIS-IS-AN-ATOM
(testal '(a b c)) ; ==> THIS-IS-A-LIST

我已经删除了 x 周围的额外括号,因为 (x) 意味着在 x 时应用函数 x表示变量 x。如果 x 处于不同的位置,例如 (+ x 3),则 + 是要应用的函数,而 x是其操作数之一。

我将 atomp 更改为 atom。由于 atom 是 50 年代第一个 LISP 定义的最早原语之一,因此它没有像大多数其他谓词那样的后缀 p

编辑:多重匹配

你可以有几个cond(或if,因为你在每个中只有一个测试)并产生副作用,比如(print "THIS-IS- AN-ATOM") 因为你的基本情况永远不会触发(在 CL 中没有什么既不是列表也不是原子)。这也许是最简单的解决方案。

(DEFUN testAL (x)
(if (ATOM x) (print 'this-is-an-atom))
(if (LISTP x) (print 'this-is-a-list)))

(testal '()) ; ==> THIS-IS-A-LIST (but prints both)

对于更实用的方法,我会使用高阶函数来完成它,以保持代码可测试并提供一个打印函数来产生副作用。请注意,这对于初学者来说可能不那么容易阅读:

;; a list of pairs of predicate and their desription
(defparameter *type-predicates-and-description*
'((douglasp . this-is-the-answer-to-everything)
(floatp . this-is-a-floating-pont-number)
(integerp . this-is-an-integer)
(numberp . this-is-a-number)
(null . this-is-null)
(listp . this-is-a-list)
(characterp . this-is-a-character)
(stringp . this-is-a-string)))

;; custom made predicate
(defun douglasp (x)
(and (numberp x) (= x 42)))

;; returns all the types of a particular value
(defun get-type-info (x)
"return a list if types thet describes argument"
(flet ((check-type (acc type-pair)
"Accumulate description when predicate match"
(if (funcall (car type-pair) x)
(cons (cdr type-pair) acc)
acc)))
;; test x for each type predicate-description
(let ((res (reduce #'check-type
*type-predicates-and-description*
:initial-value '())))
;; check of empty list (no types matched)
(if (null res)
(list 'this-is-neither)
res))))

;; test it
(get-type-info '()) ; ==> (THIS-IS-A-LIST THIS-IS-NULL)
(get-type-info 42) ; ==> (THIS-IS-A-NUMBER
; THIS-IS-AN-INTEGER
; THIS-IS-THE-ANSWER-TO-EVERYTHING)
(get-type-info #()) ; ==> (THIS-IS-NEITHER)

;; Make a function to do side effects
(defun print-type-info (x)
(format t "~{~a~^, ~}." (get-type-info x)))

(print-type-info '()) ; ==> NIL
; and prints "THIS-IS-A-LIST, THIS-IS-NULL."

关于list - 我定义的 cond 函数无法正常工作 (LISP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18647427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com