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

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

问题描述

我对一堆函数做了一些繁琐的调用,但参数将在运行时确定。我写了一个简单的函数来保持我的代码干,但给它一个名字是不必要的。我不会在其他任何地方使用这个功能。



我试图以Scheme的方式来做,但是我得到一个 void功能错误:

 (let((do(work(lambda(xyz)
(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 ...))),但这不是很可读。有更好的方法吗?

解决方案

与其他lisps(但不是Scheme)一样,Emacs Lisp具有单独的命名空间,用于变量和函数即它是一个'Lisp 2 ',而不是'Lisp 1 ';请参阅功能单元分离技术问题和价值单元格,这些术语的起源和意义)。



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

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

如果您始终发送相同数量的参数,请使用 funcall 使用应用如果您需要能够发送变量号码o f参数。



内部机制是每个符号都有多个单元格
使用哪个单元格取决于符号是评估表格
当符号是评估表单的第一个元素时,其功能单元格使用
在任何其他职位,其价值使用单元格
在您的代码中, do-work 在其值单元格中具有该函数。
要作为函数使用,您可以使用 funcall 应用
如果它在函数单元格中,您可以使用其名称作为评估表单的车辆直接调用它。
您可以通过 flet 标签 cl


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.

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))))

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

解决方案

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).

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))

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.

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天全站免登陆