1

I'm new to lisp (i'm experimenting with sbcl and ccl), i came across the use of car and cdr that can be chained arbitrarily within a single function call like (caddr).

I was wandering how one would write functions that behave like this... Say for example i'd like my-eval to eval the input s-exp 3 times if i invoke it like (my-evaaal '(+ 2 1))

I've hacked my way around with a macro like (my-ev $$$$ '(...)) where the behavior is dictated by the number of '$' in the first argument by transforming it into char sequence (coerce (symbol-name x) 'list) and the evaluate and recurse until the list is nil...

basic need:

;; if 
(defvar *foo* 1)
(eval '*foo*) ;; => 1
(eval ''*foo*) ;; => *foo*
(eval '''*foo*) ;; => '*foo*

;; then
(eval (eval (eval '''*foo*))) ;; => 1

desired syntax

(my-eval '''*foo*) ;; => '*foo*
(my-evaal '''*foo*) ;; => *foo*
(my-evaaal '''foo) ;; => 1
4

1 回答 1

4

CAAR、CADR 等函数只是常规函数;如果需要,您可以定义一个宏来帮助您轻松定义它们。

 宏

 (defpackage :so (:use :cl :ppcre))
 (in-package :so)

 (defmacro eval%% (count form)
   (case count
     (0  form)
     (1 `(eval ,form))
     (t (check-type count (integer 2))
        `(eval%% ,(1- count) (eval ,form)))))

例如,以下内容:

(eval%% 3 '''most-positive-fixnum)

依次展开为:

(EVAL%% 2 (EVAL '''MOST-POSITIVE-FIXNUM))
(EVAL%% 1 (EVAL (EVAL '''MOST-POSITIVE-FIXNUM)))
(EVAL (EVAL (EVAL '''MOST-POSITIVE-FIXNUM)))

然后,您可以按如下方式定义自定义 eval 函数,甚至可以使用另一个宏:

(defun evaal (x) (eval%% 2 x))
(defun evaaal (x) (eval%% 3 x))

处理程序并重新启动

或者,请注意您可以捕获对未定义函数的调用:

(block nil
  (handler-bind ((undefined-function
                  (lambda (e)
                    (return
                      (values (cell-error-name e)
                              (compute-restarts e))))))
    (evaaaaaal 'a)))

=> EVAAAAAAL
  (#<RESTART CONTINUE {7FD5F5F8CE43}> #<RESTART USE-VALUE {7FD5F5F8CE03}>
   #<RESTART SB-KERNEL::RETURN-VALUE {7FD5F5F8CDC3}>
   #<RESTART SB-KERNEL::RETURN-NOTHING {7FD5F5F8CD83}>
   #<RESTART SWANK::RETRY {7FD5F5F8DA13}> #<RESTART ABORT {7FD5F5F8DEC3}>
   #<RESTART ABORT {7FD5F5F8EB03}>)

您还可以使用标准的 USE-VALUE 重启来提供不同的函数来调用:

(defun multi-eval-handler (condition)
  (let ((name (cell-error-name condition)))
    (when (eq (symbol-package name) (find-package :so))
      (register-groups-bind ((#'length count)) ("EV\(A+\)L" (string name))
        (invoke-restart 'use-value (make-repeated-evaluator count))))))

您需要一个计算评估 N 次的辅助函数:

(defun make-repeated-evaluator (count)
  (case count
    (0 #'identity)
    (1 #'eval)
    (t (check-type count (integer 2))
       (lambda (form)
         (loop
            for value = form then (eval value)
            repeat count
            finally (return value))))))

例如:

(funcall (make-repeated-evaluator 3)
         '''most-positive-fixnum)
=> 4611686018427387903

然后,您可以拥有任意长的 eval 函数:

 (handler-bind ((undefined-function #'multi-eval-handler))
     (evaaaaaaaaaaaaaal '''''''''''''0))

现在,如果您编译代码,您将在编译时收到有关未知函数的警告,然后您可以消除警告。

于 2019-04-09T12:58:47.290 回答