假设我想要执行以下操作:
(loop for i from 1 to n do
(defun ith(lst)
(nth i lst)))
显然我真正想做的是以下内容:
(defun 1th(lst)(nth 1 lst))
(defun 2th(lst)(nth 2 lst))
(defun 3th(lst)(nth 3 lst))
(defun 4th(lst)(nth 4 lst))
......
(defun 100th(lst)(nth 100 lst))
我该怎么做?
答案 0 :(得分:8)
你走了。请注意|1th|
将返回第二个值:
(defmacro make-nths (n)
`(progn
,@(loop for i from 1 to n
collecting `(defun ,(intern (format nil "~ath" i)) (list)
(nth ,i list)))))
正如Xach在评论中指出的那样,macrolet
可能更适用于此,因为您并不真正需要全局定义的宏:
(macrolet ((make-nths (n)
`(progn
,@(loop for i from 1 to n
collect `(defun ,(intern (format nil "~ath" i)) (list)
(nth ,i list))))))
(make-nths 3)) ; choose n here
最后,这是ninjaaa非宏观解决方案的工作版本:
(loop for i from 1 to 3 ; choose n here
do (let ((i i)) ; introduce new bindings for each iteration
(setf (symbol-function (intern (format nil "~ath" i)))
(lambda (list) (nth i list)))))
答案 1 :(得分:0)
试试这个:
(loop for i from 1 to n do
(setf (symbol-function (intern (format nil "~dth" i)))
#'(lambda (lst) (nth i lst))))