遍历列表以查找数据,并构造一个字符串

iterating through a list to look up data, and construct a string

Elisp 新手,寻求帮助。

我有这个变量:

(setq bibtex-completion-additional-search-fields '(tags keywords))

然后我有一个函数,如果设置了这个变量,则需要遍历这些字段名称,并在数据记录中查找它们,将结果值连接成一个字符串,它 returns.

数据如下:

("2009-03-01 Zukin, Sharon and Trujillo, Valerie and Frase, Peter and Jackson, Danielle and Recuber, Tim and Walker, Abraham gentrification New Retail Capital and Neighborhood Change: Boutiques and Gentrification in New York City article zukin_new_2009"
 ("date" . "2009-03-01")
 ("author" . "Zukin, Sharon and Trujillo, Valerie and Frase, Peter and Jackson, Danielle and Recuber, Tim and Walker, Abraham")
 ("tags" . "gentrification, retail")
 ("title" . "New {{Retail Capital}} and {{Neighborhood Change}}: {{Boutiques}} and {{Gentrification}} in {{New York City}}")
 ("=type=" . "article")
 ("=key=" . "zukin_new_2009"))

这是我的 ATM 功能,我知道这是错误的。但是我不知道如何在 elisp 中执行此操作(我对 Python 和 Ruby 有更多经验)。

(defun bibtex-completion--get-extra-search-data (candidate)
  "Return extended search metadata as string."
  (if bibtex-completion-additional-search-fields
      ; if the data is present, pull its value(s), join into a single string
      ; TODO FIX ME, this is wrong
      (format "%s" (cl-loop
                    for field in bibtex-completion-additional-search-fields
                    collect
                    (cdr (assoc field (cdr candidate)))
                    ))))

因此对于上面的示例数据,函数应该 return 字符串“gentrification, retail”。如果该记录的关键字字段包含“foo”,则 return 字符串将是“gentrification, retail, foo”(或者可能只是 space 分隔;不确定是否重要)。

首先,数据结构中的键是字符串,而不是符号。因此,您可以更改查找字段,

(setq bibtex-completion-additional-search-fields '("tags" "keywords"))

但是,在 candidate 数据结构中使用符号作为 car 可能更好(我相信效率方面)。

将列表加入字符串的规范 elisp 是 (mapconcat #'identity ...),

(mapconcat
 #'identity
 (delq nil
       (cl-loop for field in bibtex-completion-additional-search-fields
             collect (cdr (assoc field (cdr candidate)))))
 ", ")