Common Lisp – destructuring-bind 函数的示例代码
2013-05-05 03:21
176 查看
;; This is a typical usage, for pulling apart a list (destructuring-bind (first second) '(1 2) (format t "~%~%;;; => first:~a second:~a~&" first second)) ;;; > first:1 second:2 ;; You can also pull apart improper lists: (destructuring-bind (first . second) '(1 . 2) (format t "~%~%;;; => first:~a second:~a~&" first second)) ;;; > first:1 second:2 ;; The first argument to destructuring-bind is a lambda list, but you ;; can grab the remainder by either using a dotted list: (destructuring-bind (first second . stuff) '(1 2 3 4 5) (format t "~%~%;;; => first:~a second:~a rest:~a~&" first second stuff)) ;;; => first:1 second:2 rest:(3 4 5) ;; or you can grab the remainder with &rest, just like you do for ;; functions that take a variable number of arguments: (destructuring-bind (first second &rest stuff) '(1 2 3 4 5) (format t "~%~%;;; => first:~a second:~a rest:~a~&" first second stuff)) ;;; => first:1 second:2 rest:(3 4 5) ;; It really is a lambda list, you can use default parameters: (destructuring-bind (first second &optional (third 'default)) '(1 2) (format t "~%~%;;; => first:~a second:~a third:~a~&" first second third)) ;;; => first:1 second:2 third:DEFAULT (destructuring-bind (first second &optional (third 'default)) '(1 2 3) (format t "~%~%;;; => first:~a second:~a third:~a~&" first second third)) ;;; => first:1 second:2 third:3 ;; And you can use keyword parameters: (destructuring-bind (first second &key third) '(1 2 :third 3) (format t "~%~%;;; => first:~a second:~a third:~a~&" first second third)) ;;; => first:1 second:2 third:3 ;; Finally, you can use it to 'unparse' trees as well, which is a ;; really great feature, since your variable declaration matches the ;; 'shape' of the data strucutre you're pulling apart. This technique ;; is really handy for dealing with XML after it's been converted to ;; s-expressions. (destructuring-bind (a (b (c d e (f g) h i j)) &rest remainder) '(1 (2 (3 4 5 (6 7) 8 9 10)) 11 12 13 14 15) (format t "~%~%;;; => a:~a b:~a c:~a d:~a e:~a f:~a g:~a h:~a i:~a j:~a remainder:~a ~&" a b c d e f g h i j remainder)) ;;; => a:1 b:2 c:3 d:4 e:5 f:6 g:7 h:8 i:9 j:10 remainder:(11 12 13 14 15)
Reference : http://asymmetrical-view.com/2008/09/18/destructuring-bind.html
S.K.
相关文章推荐
- Common Lisp – eq, eql, equal, equalp 函数的示例代码
- Common Lisp – assoc 函数的示例代码
- Common Lisp, incf, decf, setf, setq, defparameter, defvar 等函数的示例代码
- JS中实现简单Formatter函数示例代码
- mysql 存储过程、存储过程嵌套、自定义函数代码示例
- 【Linux C代码分享二】UDP Socket示例程序:使用fgets函数获取屏幕输入
- 使用C#调用存储过程,用函数合理组织代码,使程序更加的清晰(示例)
- Python常见文件操作的函数示例代码
- linux下的内存映射函数mmap详解及示例代码
- 定义函数指针类型,示例代码
- python利用dir函数查看类中所有成员函数示例代码
- php分页函数示例代码分享
- C++中const用于函数重载的示例代码
- Java8函数接口实现回调及Groovy闭包的代码示例
- boost库学习随记六:使用同步定时器、异步定时器、bind、成员函数回调处理、多线程的同步处理示例等
- linux下的内存映射函数mmap详解及示例代码
- JS中把字符转成ASCII值的函数示例代码
- SAP的SYSTEM的函数列表和代码示例
- Scala学习笔记18【curry化函数代码示例】
- javascript中call,apply,bind函数用法示例