scheme - 模拟 scheme 在 common lisp 中定义

标签 scheme lisp common-lisp

想知道在common lisp中如何模拟sc​​heme define,想写一个宏来模拟define。那么 cl 的 defun deparameter defvar 和 scheme 的 define 之间有什么不同,我该如何做到这一点?

最佳答案

define 在 Scheme 中不容易在 Common Lisp 中实现。它也不容易在 Scheme 中实现。它的变换在不同的范围内是不同的:

(define test value)              ; defines test, value can be anything even (lambda ..) which makes a procedur object
(define (test arg ...) body ...) ; defines the procedure test

(define (somefun)
  (define test ...)
  (define (test2 x) ...)
  ...)           

是一种奇特的写作方式:

(define (somefun)
  (letrec ((test ...)
           (test2 (lambda (x) ...))
    ...))

那么 Common Lisp 中的等价物是什么:

(define myplus otherfun)             ; (setf (symbol-function 'myplus) otherfun)
(define myplus (lambda args . body)) ; (defun myplus args . body)
(define (myplus . args) . body )     ; (defun myplus args . body)
(define value 10)                    ; (defparameter value 10)

这是我对宏的看法。这仍然不适用于内部定义:

(defmacro define (name-or-ll &body expressions)
  (flet ((dotted-to-rest (lst)
           (let ((last (last lst)))
             (if (null (cdr last))
                 lst
                 (append (butlast lst)
                         (list (car last) '&rest (cdr last)))))))

    (cond ((consp name-or-ll)             ; (define (fun a b) ...)
           `(progn 
              (defun ,(car name-or-ll) ,(dotted-to-rest (cdr name-or-ll)) ,@expressions)
              (defparameter ,(car name-or-ll) #',(car name-or-ll))))
          ((and (consp (car expressions)) ; (define fun (lambda (a b) ...)) 
                (eq (caar expressions) 'lambda))
            `(define (,name-or-ll ,@(cadar expressions)) ,@(cddar expressions)))
          (t `(let ((value ,(cons 'progn expressions)))                
                (when (functionp value)
                  (setf (symbol-function ',name-or-ll) value))
                (defparameter ,name-or-ll value))))))

(define proc (lambda (x) (* x x)))
(define myproc proc)
(define myplus #'+)
(define test 'test)
(define (testproc a b) (+ a b))
(define testproc2 (lambda (a . b) (apply myplus a b)))
(list (proc 10) (myproc 10) 
      (myplus 2 3) (testproc 2 3) 
      (testproc2 2 2 1) (funcall testproc2 2 2 1) 
      test) ; => (100 100 5 5 5 5 TEST)

关于scheme - 模拟 scheme 在 common lisp 中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28938940/

相关文章:

clojure - 现实世界中的 Lisp

scheme - 通过 FFI 调用 Raylib 时 Racket 中的 SIGSEGV MAPERR

lisp - Common Lisp 中标准对象和标准类的层次结构

Lisp:确定列表是否包含谓词

lisp - ltk 的问题(普通 lisp)

common-lisp - 对 `` ql :quickload`` and executable scripts in SBCL感到困惑

方案/ Racket 中的静态变量?

unicode - MIT Scheme 在解释器中使用特殊字符

python - Lisp翻译

lisp - 为什么在 LISP 中不需要#'(尖引号)符号?