Min*_*Lim 1 lisp syntax common-lisp
我做这个功能.
(f 3 4) (sum = 7)
(f 'a 'b) (not num!)
Run Code Online (Sandbox Code Playgroud)
我的问题是如果条件使用和运算符我该怎么做.
我试试....
(IF (and (typep a 'integer) (typep b 'integer)) (1) (0))
(IF (and ((typep a 'integer)) ((typep b 'integer))) (1) (0))
(IF ((and ((typep a 'integer)) ((typep b 'integer)))) (1) (0))
但它不起作用.(1)(0)我暂时设置它.
我可以获得一些lisp语法帮助吗?
此时你需要了解的关于Lisp的最重要的事情是parens很重要.
在C语言中,你可以写1+3,(1)+3,(((1+3)))他们都意味着同样的事情.在lisp中,它们非常不同:
a表示" 名为" 的变量的值a.(a)意思是"的返回值函数命名a称为不带任何参数".((a)) 是语法错误(但请参阅PPS)因此,每个版本((...))都是完全错误的.
由于没有命名1的函数,第一个版本也没有好处.
你需要的是:
(if (and (typep a 'integer)
(typep b 'integer))
1
0)
Run Code Online (Sandbox Code Playgroud)
注意格式和缩进.Lispers通过缩进读取代码,而不是 parens,因此适当的缩进是至关重要的.请注意,Emacs(可能还有一些其他特定于Lisp的IDE)会为您缩进lisp代码.
PS.您要完成的内容的描述尚不清楚,但最简单的方法可能是使用泛型函数:
(defgeneric f (a b)
(:method ((a integer) (b integer))
(+ a b)))
(f 1 2)
==> 3
(f 1 'a)
*** - NO-APPLICABLE-METHOD: When calling #<STANDARD-GENERIC-FUNCTION F> with
arguments (1 A), no method is applicable.
Run Code Online (Sandbox Code Playgroud)
PPS.最终你会看到合法的((...) ...),例如cond:
(defun foo (a)
(cond ((= a 1) "one")
((= a 2) "two")
(t "many")))
(foo 1)
==> "one"
(foo 3)
==> "many"
Run Code Online (Sandbox Code Playgroud)
或lambda形式:
((lambda (x) (+ x 4)) 5)
==> 9
Run Code Online (Sandbox Code Playgroud)
但你还不用担心这些.