我正在修改 Emacs 模式。 https://github.com/bigos/git-auto-commit-mode
我是 Emacs lisp 新手,我找不到解决以下问题的优雅解决方案。
我有这个代码片段,其中函数 gac-raw-branches 返回一个字符串或 nil,并且我找不到好的解决方案来避免 split 需要字符串的错误。我使用以下示例中所示的 gac-split-for-current 等辅助函数。但是,有更好的方法吗?
(defun gac-split-for-current-branch (raw-branches)
(split-string raw-branches "\n"))
(defun gac-current-branch (filename)
"Current git branch of FILENAME."
(let ((res)
(raw-branches (gac-raw-branches filename)))
(if raw-branches
(dolist (el
(gac-split-for-current-branch raw-branches)
res)
(if (string-match "^\\* .*" el)
(setq res (substring el 2))))
nil)))
最佳答案
这是漂亮的(IMO)代码:
(defun gac-current-branch (filename)
"Current git branch of FILENAME."
(let (res)
(dolist (el (ignore-errors
(split-string
(gac-raw-branches filename)
"\n" t)))
(when (string-match "^\\* +\\(.*\\)$" el)
(setq res (match-string 1 el))))
res))
我也有点喜欢函数式风格,尽管不推荐用于 Elisp:
(defun gac-current-branch (filename)
"Current git branch of FILENAME."
(cl-reduce
(lambda (res el)
(or (and (string-match "^\\* +\\(.*\\)$" el)
(match-string 1 el))
res))
(ignore-errors
(split-string (gac-raw-branches filename) "\n" t))))
几点:
- 我不喜欢定义只是一个函数的部分应用的函数,例如
gac-split-for-current-branch
。它使代码不太清晰。 (ignore-errors (split-string x))
始终返回一个列表,nil
位于 最糟糕的。可以使用dolist
或nil
进行迭代mapcar
或cl-reduce
。- 无需在
if
语句的 else 子句中写入nil
:它是自动的。
关于Emacs Lisp - 如何处理函数返回字符串或 nil 的边缘情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27369794/