Lisp,说明在defun中不起作用 [英] Lisp, instructions not working in defun
问题描述
我正在尝试制作一个将中缀输入更改为前缀的函数,例如:(x + 1)
作为以(+ x 1)
输出的输入.
I'm trying to make a function that changes infix input to prefix eg : (x + 1)
as input outputted as (+ x 1)
.
所以这是我目前的代码:
So here is my code for the moment :
(setq x '(Y + 1))
(if (listp x ) (list (second x) (first x) (first (last x))) x)
因此,如果我输入列表,则返回(+ Y 1)
;如果不是列表,则返回用户输入.
so it returns (+ Y 1)
if I input a list and the user input if it's not a list.
但是,问题是我无法在函数中使用此代码:
However, the problem is that I can't get this code working in a function :
(defun prefixToInfix (x)(
(if (listp x ) (list (second x) (first x) (first (last x))) x)
)
)
该函数确实已创建,但是当我调用它时
the function is indeed created but when I call it
(prefixtoinfix '(Y + 1))
我收到错误
Error: Illegal function object: (IF (LISTP X) (LIST # # #) X).
[condition type: TYPE-ERROR]
我不知道为什么if语句在主程序中起作用,但是当我从函数中运行它时却不起作用.
I don't know why my if statement works in the main program but doesn't when I run it from my function.
推荐答案
您所缺少的是Lisp括号中的有意义.
What you are missing is that in Lisp parentheses are meaningful.
在C/Java/Python& c中,以下表达式相同:
In C/Java/Python &c, the following expressions are the same:
a+b
(a+b)
(a)+(b)
(((a)+(b)))
(((((a)+(b)))))
在Lisp中,以下表达式非常不同:
In Lisp, the following expressions are very different:
-
a
---一个符号 -
(a)
---具有单个元素的列表,该元素是符号a
-
(1 (2))
---两个元素的列表:
a
--- a symbol(a)
--- a list with a single element, which is the symbola
(1 (2))
--- a list of two elements:
- 编号
1
- 长度为1的列表,包含数字
2
- number
1
- list of of length 1, containing number
2
以您的情况为例,功能(请注意缩进和括号的位置!)
In your case, function (note indentation and paren placement!)
(defun prefixToInfix (x)
((if (listp x) (list (second x) (first x) (first (last x))) x)))
在if
周围有多余的括号(这会导致整个if
形式被解释为一个函数,导致灾难性的结果),应该是(请注意换行符和缩进-lispers不计算括号),它们看起来缩进以了解代码,请参见 http://lisp-lang.org/style-guide/)
has extra parens around if
(and this causes the whole if
form to be interpreted as a function, with disastrous results), and should be (note line breaks and indentation - lispers do not count parens, they look at indentation to understand the code, see http://lisp-lang.org/style-guide/)
(defun prefix-to-infix (x)
(if (listp x)
(list (second x)
(first x)
(first (last x)))
x))
PS.另请参见想要学习常见的口吻的建议.
这篇关于Lisp,说明在defun中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!