upg*_*grd 2 lisp common-lisp cl
David Touretzky 的 Common Lisp 书中的练习 6.36 要求一个函数swap-first-last
来交换任何列表的第一个和最后一个参数。我现在觉得很愚蠢,但我无法用destructuring-bind
.
我如何在 Pythonfirst, *rest, last = (1,2,3,4)
中执行 Common Lisp/with 中的操作(可迭代解包)destructuring-bind
?
毕竟尝试过,加上@WillNess 的一些评论(谢谢!),我想出了这个想法:
bind
这个想法是尝试细分列表并在 中使用&rest
lambda 列表的功能destructuring-bind
,但是,使用较短的.
符号 - 以及 usingbutlast
和car
-last
组合。
(defmacro bind ((first _rest last) expr &body body)
`(destructuring-bind ((,first . ,_rest) ,last)
`(,,(butlast expr) ,,(car (last expr)))
,@body)))
Run Code Online (Sandbox Code Playgroud)
用法:
(bind (f _rest l) (list 1 2 3 4)
(list f _rest l))
;; => (1 (2 3) 4)
Run Code Online (Sandbox Code Playgroud)
没有像 Python 那样优雅的可能性。
destructuring-bind
不能比 lambda 更不同地绑定:lambda 列表仅将整个其余部分视为&rest <name-for-rest>
. 没有办法直接取出最后一个元素。(当然,没办法,除非你为这类问题额外写了一个宏)。
(destructuring-bind (first &rest rest) (list 1 2 3 4)
(let* ((last (car (last rest)))
(*rest (butlast rest)))
(list first *rest last)))
;;=> (1 (2 3) 4)
;; or:
(destructuring-bind (first . rest) (list 1 2 3 4)
(let* ((last (car (last rest)))
(*rest (butlast rest)))
(list first *rest last)))
Run Code Online (Sandbox Code Playgroud)
但是,当然,您使用的是 lisp,理论上您可以destructuring-bind
以更复杂的方式编写宏
...
但是,destructuring-bind
并没有比以下更清晰:
(defparameter *l* '(1 2 3 4))
(let ((first (car *l*))
(*rest (butlast (cdr *l*)))
(last (car (last *l*))))
(list first *rest last))
;;=> (1 (2 3) 4)
Run Code Online (Sandbox Code Playgroud)
first-*rest-last
为了向您展示,在普通的 lisp 中,生成这样一个宏的速度有多快:
;; first-*rest-last is a macro which destructures list for their
;; first, middle and last elements.
;; I guess more skilled lisp programmers could write you
;; kind of a more generalized `destructuring-bind` with some extra syntax ;; that can distinguish the middle pieces like `*rest` from `&rest rest`.
;; But I don't know reader macros that well yet.
(ql:quickload :alexandria)
(defmacro first-*rest-last ((first *rest last) expr &body body)
(let ((rest))
(alexandria:once-only (rest)
`(destructuring-bind (,first . ,rest) ,expr
(destructuring-bind (,last . ,*rest) (nreverse ,rest)
(let ((,*rest (nreverse ,*rest)))
,@body))))))
;; or an easier definition:
(defmacro first-*rest-last ((first *rest last) expr &body body)
(alexandria:once-only (expr)
`(let ((,first (car ,expr))
(,*rest (butlast (cdr ,expr)))
(,last (car (last ,expr))))
,@body))))
Run Code Online (Sandbox Code Playgroud)
用法:
;; you give in the list after `first-*rest-last` the name of the variables
;; which should capture the first, middle and last part of your list-giving expression
;; which you then can use in the body.
(first-*rest-last (a b c) (list 1 2 3 4)
(list a b c))
;;=> (1 (2 3) 4)
Run Code Online (Sandbox Code Playgroud)
此宏允许您为first
,*rest
和last
列表的一部分提供任何名称,您可以在宏的主体中进一步处理这些名称,希望有助于提高代码的可读性。
归档时间: |
|
查看次数: |
343 次 |
最近记录: |