gpt4 book ai didi

scheme - 模拟 scheme 在 common lisp 中定义

转载 作者:太空宇宙 更新时间:2023-11-03 18:51:45 25 4
gpt4 key购买 nike

想知道在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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com