【问题标题】:Various forms of looping and iteration in ElispElisp中各种形式的循环和迭代
【发布时间】:2020-08-07 17:29:31
【问题描述】:

我试图了解 Emacs Lisp 中的所有循环结构。 在一个示例中,我尝试遍历符号列表并将它们打印到 *message* 缓冲区,如下所示:

(let* ((plist package-activated-list) ;; list of loaded packages
       (sorted-plist (sort plist 'string<)))
  (--map (message (format "%s" it)) sorted-plist))

--mapdash.el 包中的一个函数。

如何在纯 Elisp 中做到这一点?

现在我如何在 Elisp 中迭代一个列表,而不使用其他包。

我见过一些使用whiledolist 宏的例子,例如这里:

https://www.gnu.org/software/emacs/manual/html_node/elisp/Iteration.html

但这些都是破坏性的、非功能性的方式来表达循环。

来自Scheme(大约 20 年前曾与它和 SICP 合作过!),我倾向于更喜欢功能性、非破坏性(是否总是导致递归?)表达想法的方式。

那么在 Emacs Lisp 中遍历项目列表的惯用方法是什么?

另外:有没有办法在 Emacs Lisp 中以函数方式表达循环?

到目前为止我发现了什么

  1. 循环宏(来自 Common Lisp?)前缀为“cl-*”

https://www.gnu.org/software/emacs/manual/html_node/cl/Loop-Facility.html

  1. 迭代子句

https://www.gnu.org/software/emacs/manual/html_node/cl/Iteration-Clauses.html#Iteration-Clauses

  1. Dash.el

https://github.com/magnars/dash.el

Magnar Sveen 的出色软件包以“Emacs 的现代列表 api。不需要 'cl。”进行营销。

还有什么?有什么推荐的读物吗?

【问题讨论】:

    标签: lisp elisp


    【解决方案1】:

    您可以探索一堆原生的 ~map~ 函数来迭代列表,其中包含一些 subbtilities 或糖。

    在这种情况下,我选择 `mapconcat',它是从 C 代码加载的。

    (mapconcat #'message sorted-plist "\n")

    【讨论】:

    【解决方案2】:

    dolist 没有破坏性,这可能是 Emacs Lisp 或 Common Lisp 中最惯用的方式,当您只想对每个成员依次执行某项操作时循环列表:

    (setq *properties* '(prop1 prop2 prop3))
    
    (dolist (p *properties*)
      (print p))
    

    seq-doseq 函数与dolist 做同样的事情,但接受序列参数(例如,列表、向量或字符串):

    (seq-doseq (p *properties*)
      (print p))
    

    如果需要更实用的样式,seq-do 函数将函数应用于序列的元素并返回原始序列。这个函数类似于Scheme过程for-each,也用于它的副作用。

    (seq-do #'(lambda (p) (print p)) *properties*)
    

    【讨论】:

      【解决方案3】:

      如果你正在寻找更传统的 Lisp map 函数,e-lisp 有它们:

      https://www.gnu.org/software/emacs/manual/html_node/elisp/Mapping-Functions.html#Mapping-Functions

      在您的代码 sn-p 中,mapc 可能是您想要的(丢弃值,只应用函数;如果您想要值,mapcar 仍然存在):

      (mapc #'(lambda (thing) (message (format "%s" thing))) sorted-plist)
      

      【讨论】:

      • 除了(format "%s" it) 在这里不起作用,因为it 只在dash.el 中起作用。
      • 你是对的。在发布之前应该更仔细地检查我的代码。将编辑。
      猜你喜欢
      • 2021-01-01
      • 2017-07-13
      • 2017-01-10
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 2015-11-14
      相关资源
      最近更新 更多