[英]The format function looping over a dotted alist
我正在开发一个将alist转换为查询参数的函数。 到目前为止它看起来像这样。
(defun encode-options (opts)
"Turns an alist into url query parameters."
(format nil "~{~{~A=~A~}~^&~}" opts))
这适用于像((ab) (cd))
(导致"A=B&C=D"
)这样的列表,但对于像((a . b) (c . d))
a.b ((a . b) (c . d))
c.d))这样的虚线列表则失败。 (结果是The value B is not of type LIST.
)
我的问题是: 是否可以format
虚线列表以给出预期结果以及如何?
是否可以格式化虚线列表?
不,格式遍历正确的列表。
有许多可能的方法来实现您想要的。 我在这里介绍其中两个。
(defun ensure-proper-list (value)
(typecase value
(null nil)
(cons (cons (car value)
(ensure-proper-list (cdr value))))
(t (list value))))
现在,您转换选项参数,以便所有元素都是正确的列表:
(defun encode-options (options)
"Turns an alist into url query parameters."
(format nil
"~{~{~A=~A~}~^&~}"
(mapcar #'ensure-proper-list options)))
(defun print-alist (stream data &optional colonp atsignp)
(declare (ignore colonp atsignp))
(destructuring-bind (head . tail) data
(format stream "~A=~A" head (if (consp tail) (first tail) tail))))
使用此新格式控件,按以下方式打印列表:
(defun encode-options (options)
"Turns an alist into url query parameters."
(format nil
"~{~/lib:print-alist/~^&~}"
options))
请注意,我添加了一个包前缀lib
因为没有包, print-alist
将在用户包(也就是COMMON-LISP-USER)中查找,在我看来很少是你想要的。 从22.3.5.4 Tilde Slash:调用函数 :
通过在指示的包中查找具有指示名称的符号来获得对应于〜/ name /指令的功能。 如果name不包含“:”或“::”,则在COMMON-LISP-USER包中查找整个名称字符串。
这就是为什么我建议总是提到带有~/
指令的包。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.