gpt4 book ai didi

lisp - 如何告诉 lisp 阅读器函数在解析过程中忽略错误

转载 作者:太空宇宙 更新时间:2023-11-03 18:56:43 24 4
gpt4 key购买 nike

我需要一种方法来抑制在使用 read-from-string 解析代码时引发的任何错误消息,以便我可以使用类似这样的方法从 Clojure 代码中读取:

(let* ((string-with-code "  '(func UpperCase \"string\")")
(brace-pos (position #\( string-with-code))
(end-of-token (+ brace-pos
(position #\Space (subseq string-with-code brace-pos))))
(first-token (subseq string-with-code (incf brace-pos) end-of-token)))
(format t "Found function: '~a'"
(read-from-string first-token)))
;; ==> Found function: 'func'

它基本上从字符串中的 lisp 代码打印函数名称。它工作正常,直到您尝试使用点运算符 (.) 作为列表中的第一项。 Clojure 使用 .cons 并访问 Java 包中的类,因此有效代码如下:

(defmacro chain
([x form] `(. ~x ~form))
([x form & more] `(chain (. ~x ~form) ~@more)))

会导致错误:

*** - READ from #<INPUT STRING-INPUT-STREAM>: token "." not allowed here

如果我要遍历它打印代码中的每个函数。我想要一种方法来忽略/抑制来自 read-from-string 的错误消息,以便此代码在不修改 lisp 阅读器工作方式的情况下更好地工作。

编辑:

一个完整的程序:

(defvar string-with-code "(defmacro chain
([x form] `(d ~x ~form))
([x form & more] `(chain (. ~x ~form) ~@more)))
")

(defvar end-of-token 0)
(defvar first-token 0)

(defun functions-in-string (code)
(let ((bpos (position #\( code)))
(unless (null bpos)
(setq end-of-token (+ bpos (position #\Space (subseq code bpos))))
(setq first-token (subseq code (incf bpos) end-of-token))
(ignore-errors
(format t "Found function: '~(~A~)'~%" (read-from-string first-token)))
(functions-in-string (subseq code end-of-token)))))

;; (ignore-errors
;; (functions-in-string 0 code))

(functions-in-string string-with-code)

输出:

Found function: 'defmacro'
Found function: '[x'
Found function: 'd'
Found function: '[x'
Found function: 'chain'
;; You'll get the error below if ignore-errors wraps around the function call
;; *** - READ from #<INPUT STRING-INPUT-STREAM>: token "." not allowed here

最佳答案

不清楚你在问什么,但忽略错误只是:

CL-USER 37 > (ignore-errors (read-from-string "(. foo bar)"))
NIL
#<CONDITIONS:SIMPLE-READER-ERROR 402000243B>

如果出现错误,IGNORE-ERRORS 返回 NIL 并且作为第二个返回值条件。

如果你想要更多的控制,你需要编写一个错误处理程序。

关于lisp - 如何告诉 lisp 阅读器函数在解析过程中忽略错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20081683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com