Ruby 我如何定义函数“取”;积木;作为elisp中的参数?

Ruby 我如何定义函数“取”;积木;作为elisp中的参数?,ruby,elisp,Ruby,Elisp,在Ruby中,方法可以采用blocks/lambda,使您能够编写类似于语言一部分的结构。例如,Fixnum类上的times方法: 2.times do # whatever code is between do and end, will be executed 2 times end File.open(some_file) do |file| # do something with the file; once the block finishes execution, the

在Ruby中,方法可以采用blocks/lambda,使您能够编写类似于语言一部分的结构。例如,
Fixnum
类上的
times
方法:

2.times do
  # whatever code is between do and end, will be executed 2 times
end
File.open(some_file) do |file|
   # do something with the file; once the block finishes execution, the handle is automatically closed
end
或者,例如,
文件
类中的
打开
方法:

2.times do
  # whatever code is between do and end, will be executed 2 times
end
File.open(some_file) do |file|
   # do something with the file; once the block finishes execution, the handle is automatically closed
end
open方法可以有类似的实现(请原谅Ruby的“伪代码”):

我怎样才能在elisp中编写这样的函数/方法,以便在使用它们时,只需要关心任务的“相关”部分,而不必一直查看所有的样板文件

如何在elisp中编写这样的函数/方法,以便在使用 他们,我只需要关心任务的"相关"部分,, 而不是一直看所有的样板文件

您可以使用宏来实现这一点

例如,如果没有
dotimes
,您可以自己轻松编写类似的内容:

(defmacro do-times (n &rest body)
  (let ((i (gensym)))
    `(do ((,i 0 (1+ ,i)))
         ((= ,i ,n))
       ,@body)))
现在,
(dotimes3(princ'x))
将完成您期望的操作(您可能需要
(require'cl)

这是通过编写代码为您编写样板来实现的。我不会在这里给你一个完整的宏教程——一个快速的谷歌搜索将为你提供足够的教程和其他信息

您可以对文件处理执行相同的操作。查看带有临时文件的
,了解emacs lisp示例。例如,在CL中,有一个带有openfile的
,它的功能与您的第二个Ruby代码片段几乎相同。因此:

File.open(some_file) do |file|
   # do something with the file; once the block finishes execution, the handle is automatically closed
end
变成:

(with-open-file (file "some_file")
  # do something ...
  )
除了可以对宏进行语法抽象外,还可以编写更高阶的函数:

(defun times (n function)
  (do-times n (funcall function)))
现在,此函数将接受计数和另一个函数,该函数将执行
n
次<代码>(times 3(lambda()(princ'x))
将实现您所期望的功能。或多或少,Ruby块只是这类东西的语法糖