我在这里遇到一个小问题,
我一直收到错误,我似乎无法弄清楚为什么,
代码应该改变列表的范围,
所以,如果我们给它一个值为(1 2 3 4)
的列表,并且我们想要将范围从11改为14,那么结果将是(11 12 13 14)
问题是最后一个名为scale-list
的函数会回复错误说:
调试器输入 - Lisp错误:(错误的类型参数number-or-marker-p nil)
任何人都知道为什么? 我使用aquamacs作为编辑 提前谢谢
;;finds minimum in a list
(defun minimum (list)
(car (sort list #'<)))
;;finds maximum in a list
(defun maximum (list)
(car (sort list #'>)))
;;calculates the range of a list
(defun range (list)
(- (maximum list) (minimum list)))
;;scales one value to another range
(defun scale-value (list low high n)
(+ (/ (* (- (nth (- n 1) list)
(minimum list))
(- high low))
(range list))
low))
;;is supposed to scale the whole list to another range
(defun scale-list (list low high n)
(unless (= n 0)
(cons (scale-value list low high n)
(scale-list list low high (- n 1)))))
(scale-list '(1 2 3 4) 21 24 4)
答案 0 :(得分:4)
需要改进最大值和最小值的定义。 SORT是破坏性的。用类似'(1 2 3 4)的字面常量调用SORT也是错误的 - 再次,SORT是破坏性的。
更好的定义:
(defun minimum (list)
(reduce #'min list))
(defun maximum (list)
(reduce #'max list))
更有效的范围定义:
(defun range (list)
(loop for e in list
maximize e into max
minimize e into min
finally (return (- max min))))
SCALE-LIST和SCALE-VALUE也不像Lisp一样。 如果你在递归函数中像这样调用NTH那么就会出错。你应该对列表进行递归,而不是索引。 SCALE-VALUE为每个呼叫调用RANGE和MINIMUM。为什么呢?
检查此变体:
;;scales one value to another range
(defun scale-value (item low high min range)
(+ (/ (* (- item min)
(- high low))
range)
low))
;;is supposed to scale the whole list to another range
(defun scale-list (list low high)
(let ((min (minimum list))
(range (range list)))
(labels ((scale-list-aux (list)
(when list
(cons (scale-value (first list) low high min range)
(scale-list-aux (rest list))))))
(scale-list-aux list))))
(scale-list '(1 2 3 4) 21 24)
你还能提高多少?例如,我将摆脱递归并用MAPCAR替换它。
答案 1 :(得分:0)
我发布代码是因为出了问题......
;;finds minimum in a list
(defun minimum(list)
(car (sort list #'<)))
;;finds maximum in a list
(defun maximum(list)
(car (sort list #'>)))
;;calculates the range of a list
(defun range(list)
(- (maximum list) (minimum list)))
;;scales one value to another range
(defun scale-value(list low high n)
(+ (/ (* (- (nth (- n 1) list) (minimum list)) (- high low)) (range list)) low))
;;is supposed to scale the whole list to another range
(defun scale-list(list low high n)
(unless (= n 0)
(cons (scale-value list low high n) (scale-list list low high (- n 1)))))
(scale-list '(1 2 3 4) 21 24 4)
答案 2 :(得分:0)
您的实际堆栈跟踪类似于:
-(nil 0.1)
(* (- (nth ... list) (minimum list)) (- high low))
(/ (* (- ... ...) (- high low)) (range list))
(+ (/ (* ... ...) (range list)) low)
scale-value((0.1) 20 30 3)
我猜你确定了一个错误的第n个元素,这会返回nil,这会使减法变得混乱。