为什么我的lisp代码给我...应该是lambda表达式? [英] Why does my lisp code give me ...should be a lambda expression?
问题描述
(defun helper-2 (list)
(if (null (first (rest list)))
0)
(+ (distance ((car list) (first (rest list))))
(helper-2 (rest list))))
我是Lisp的新手,我正在编写一个程序来计算任何多边形的周长,并按顺时针方向输入.我的逻辑是,我使用辅助方法来计算彼此相邻的两个点的长度并求和.递归完成后,我将做一个单独的调用来计算从起点到终点的长度,并对所有内容求和.我已经完成了距离方法,该方法需要2点并返回长度.
I'm new to lisp and I'm writing a program to compute the perimeter of any polygon with input following clockwise order. My logic is that I use a helper method to compute the length of two points next to each other and do the sum. After recursion is done, I will do a separate call to calculate the length from the beginning point to its end and sum everything up. I've finished the distance method which takes 2 points and return the length.
(distance '(2 0) '(4 0)) ;this will output 2
helper-2逻辑: 假设我们有3个点a(2 0)b(3 3)c(4 0)这种方法可以总结ab和bc之间的距离.但是,我不断收到(车头)应该是lambda表达式"错误.有人可以帮忙吗?谢谢你.还是有人可以给我一种更好的方法来计算多边形的周长?
helper-2 logic: assume we have 3 points a (2 0) b (3 3) c (4 0) This method is expected to sum up the distance between ab and bc. However, I keep getting "(car head) should be a lambda expression" error. Can anyone help? Thank you. Or could anyone give me a better way to compute the perimeter of a polygon?
(defun square (n) (* n n))
(defun distance (a b)
(let ((h (- (second b) (second a)))
(w (- (first b) (first a))))
(sqrt (+ (square h) (square w)))))
推荐答案
您的helper-2
函数在两个地方是错误的:
Your helper-2
function is wrong in two places:
- 您应该使用两臂式
if
,这样它就可以充当if/else. -
(car list)
周围的括号太多.
- You should be using a two-armed
if
, so that it functions as an if/else. - You have too many parentheses around the
(car list)
.
这是固定版本:
(defun helper-2 (list)
(if (null (first (rest list)))
0
(+ (distance (car list) (first (rest list)))
(helper-2 (rest list)))))
这篇关于为什么我的lisp代码给我...应该是lambda表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!