如何突破Emacs Lisp中的maphash?

Ger*_*ann 2 emacs elisp

我需要maphash在找到我要找的东西时提前退出.

(defun find-in-hash (str hash)
  (let ((match nil))
    (maphash (lambda (key value)
      (if (string-prefix-p str key)
        (setq match key))) hash)
    match))
Run Code Online (Sandbox Code Playgroud)

我将如何在Emacs Lisp中执行此操作?

N.N*_*.N. 6

正如在如何中断maphash中所解释的那样,您可以maphash在块内部放置并通过块退出块return-from,即使用表单

(block stop-mapping
  (maphash
   ;; Function to call for all entries in ht.
   ;; A condition for when to stop mapping.
     (return-from stop-mapping)
   ht))
Run Code Online (Sandbox Code Playgroud)

请注意,这需要cl通过哪些方法(require 'cl).正如评论中所提到的,在纯粹的elisp via中可以实现相同的结果

(catch 'stop-mapping
  (maphash
   ;; Function to call for all entries in ht.
   ;; A condition for when to stop mapping.
     (throw 'stop-mapping retval)
   ht))
Run Code Online (Sandbox Code Playgroud)

  • 它们只有在你('需要'cl)`之后才可用.很可能你正在使用的其他软件包已经完成了`require`,这就是你看到它们的原因.在任何情况下,`block`和`return-from`是在`cl`包中实现的宏,它们扩展为使用`catch`和`throw`的代码. (3认同)