如何在 Emacs Lisp 中创建临时函数 [英] How to Create a Temporary Function in Emacs Lisp

查看:28
本文介绍了如何在 Emacs Lisp 中创建临时函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对一堆函数进行一些乏味的调用,但参数将在运行时确定.我写了一个简单的函数来保持我的代码 DRY 但给它一个名字是不必要的.我不会在其他任何地方使用此功能.

I'm making some tedious calls to a bunch of functions, but the parameters will be determined at runtime. I wrote a simple function to keep my code DRY but giving it a name is unnecessary. I don't use this function anywhere else.

我正在尝试按照我在 Scheme 中的方式进行操作,但出现 void-function 错误:

I'm trying to do it the way I would in Scheme, but I get a void-function error:

(let ((do-work (lambda (x y z)
                  (do-x x)
                  (do-y y)
                  ;; etc
                  )))
  (cond (test-1 (do-work 'a 'b 'c))
        (test-2 (do-work 'i 'j 'k))))

我可以将它全部粘贴到 apply(例如,(apply (lambda ...) (cond ...)))但那不是很可读.有没有更好的办法?

I could stick it all into an apply (e.g., (apply (lambda ...) (cond ...))) but that isn't very readable. Is there a better way?

推荐答案

与其他 lisp(但不是 Scheme)一样,Emacs Lisp 为变量和函数拥有单独的命名空间(即它是一个 'Lisp2',而不是'Lisp1';见功能细胞和值细胞分离的技术问题 为这些的起源和意义条款).

Like other lisps (but not Scheme), Emacs Lisp has separate namespaces for variables and functions (i.e. it is a ‘Lisp2’, not a ‘Lisp1’; see Technical Issues of Separation in Function Cells and Value Cells for the origin and meaning of these terms).

您将需要使用 funcallapply 来调用存储在变量中的 lambda(或其他函数).

You will need to use funcall or apply to call a lambda (or other function) that is stored in a variable.

(cond (test-1 (funcall do-work 'a 'b 'c))
      (test-2 (funcall do-work 'i 'j 'k))

如果您将始终发送相同数量的参数,请使用 funcall.如果您需要能够发送可变数量的参数,请使用 apply.

Use funcall if you will always send the same number of arguments. Use apply if you need to be able to send a variable number of arguments.

内部机制是每个符号都有多个单元格".使用哪个单元格取决于 符号在评估中的位置形式.当符号是评估形式的第一个元素时,其使用功能"单元格.在任何其他位置,使用其值"单元格.在您的代码中, do-work 在其值单元格中具有该函数.要将其作为函数访问,请使用 funcallapply.如果它在函数单元格中,您可以通过使用其名称作为评估形式的汽车来直接调用它.您可以使用 flet 完成此操作或 cl 包中的 labels.

The internal mechanism is that each symbol has multiple "cells". Which cell is used depends on where the symbol is in an evaluated form. When a symbol is the first element of an evaluated form, its "function" cell is used. In any other position, its "value" cell is used. In your code, do-work has the function in its value cell. To access it as a function you use funcall or apply. If it were in the function cell, you could call it directly by using its name as the car of an evaluated form. You can accomplish this with flet or labels from the cl package.

这篇关于如何在 Emacs Lisp 中创建临时函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆