LISP函数,给定一个数字和一个列表,返回大于n的第一个偶数
我找不到我的错误。 这会不断返回LISP函数,给定一个数字和一个列表,返回大于n的第一个偶数,lisp,common-lisp,Lisp,Common Lisp,我找不到我的错误。 这会不断返回nil: (even-greater-n 5 '(1 2 3 4 5 6 7)) (defun even-greater-n (n L) (cond ((null L) nil) ((and (> (car L) n) (evenp n)) (car L)) (t (even-greater-n n (cdr L))))) 你的错误 您正在传递到n 而不是(汽车L) 迭代 这是相对容易实现的使用 : 你的错误 您
nil
:
(even-greater-n 5 '(1 2 3 4 5 6 7))
(defun even-greater-n (n L)
(cond ((null L) nil)
((and (> (car L) n) (evenp n)) (car L))
(t (even-greater-n n (cdr L)))))
你的错误
您正在传递到n
而不是(汽车L)
迭代
这是相对容易实现的使用
:
你的错误
您正在传递到n
而不是(汽车L)
迭代
这是相对容易实现的使用
:
您必须查找
(左车)
是否为偶数。您必须查找(左车)
是否为偶数。使用find if
和单个打开编码的lambda函数:
(defun even-greater (n list)
(find-if (lambda (item) (and (> item n) (evenp item))) list))
使用函数组合器:
;; Combine multiple functions with AND:
;; Returns a function of one-argument which
;; passes that argument to the functions in the list,
;; one by one. If any function returns nil, it stops
;; and returns nil. Otherwise it returns the value
;; returned by the last function:
(defun andf (&rest functions)
(lambda (arg)
(let (res)
(dolist (f functions res)
(unless (setf res (funcall f arg))
(return))))))
;; Returns a one-argument function which tests
;; whether its argument is greater than quant.
(defun greater (quant)
(lambda (arg) (> arg quant)))
;; "find it, if it is greater than n, and even"
(defun even-greater (n list)
(find-if (andf (greater n) #'evenp) list))
使用
find if
和单个开放编码lambda函数:
(defun even-greater (n list)
(find-if (lambda (item) (and (> item n) (evenp item))) list))
使用函数组合器:
;; Combine multiple functions with AND:
;; Returns a function of one-argument which
;; passes that argument to the functions in the list,
;; one by one. If any function returns nil, it stops
;; and returns nil. Otherwise it returns the value
;; returned by the last function:
(defun andf (&rest functions)
(lambda (arg)
(let (res)
(dolist (f functions res)
(unless (setf res (funcall f arg))
(return))))))
;; Returns a one-argument function which tests
;; whether its argument is greater than quant.
(defun greater (quant)
(lambda (arg) (> arg quant)))
;; "find it, if it is greater than n, and even"
(defun even-greater (n list)
(find-if (andf (greater n) #'evenp) list))
这是因为你在检查
n
是否为偶数,而在你的测试中它是5
并且永远不会偶数这是因为你在检查n
是否为偶数,而在你的测试中它是5
并且永远不会偶数。。
;; Combine multiple functions with AND:
;; Returns a function of one-argument which
;; passes that argument to the functions in the list,
;; one by one. If any function returns nil, it stops
;; and returns nil. Otherwise it returns the value
;; returned by the last function:
(defun andf (&rest functions)
(lambda (arg)
(let (res)
(dolist (f functions res)
(unless (setf res (funcall f arg))
(return))))))
;; Returns a one-argument function which tests
;; whether its argument is greater than quant.
(defun greater (quant)
(lambda (arg) (> arg quant)))
;; "find it, if it is greater than n, and even"
(defun even-greater (n list)
(find-if (andf (greater n) #'evenp) list))