Dotted Formatting Function

I am working on a function that converts alist to query parameters. So far it looks like this.

(defun encode-options (opts)
  "Turns an alist into url query parameters."
  (format nil "~{~{~A=~A~}~^&~}" opts))

This works great for alists such as ((a b) (c d))(result "A=B&C=D"), but is not suitable for point-like alists such as ((a . b) (c . d)). (Result The value B is not of type LIST.)

My question is: Is it possible for a formatdotted alist to give me the expected results and how?

+4
source share
1 answer

Can I format a dotted list?

No, formats iterations on the corresponding lists.

There are many possible ways to implement what you want. Here I present two of them.

Save control bar, change data

(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 (a.k.a. COMMON- LISP -USER), , , , . 22.3.5.4 Tilde Slash: :

, ~/name/, . ":" "::", COMMON- LISP -USER.

~/.

+6
source

Source: https://habr.com/ru/post/1654803/


All Articles