【发布时间】:2021-07-11 20:32:37
【问题描述】:
我正在尝试从流中读取“单词”。一个词只是一个数字“1234”、一个常用的字母字符词“test”和用撇号“you're”的常用词的缩写。
当然,有数十亿种方法可以做到这一点。我正在尝试使用tagbody 来实现类似状态机的东西来解析单词。如果给出了正确的输入,但对于与单词不相似的输入,我的实现就可以工作。我试图跳过输入,直到达到新的空白或 eof,但这给了我一个无限循环,我不知道为什么。
谁能解释一下?
这是我的代码
(defun whitespace-or-nil-p (c)
"Returns if a character is whitespace"
(member c '(#\ #\Tab #\Return #\Newline nil)))
(defun read-word (stream)
(let ((c nil))
(with-output-to-string (out)
(tagbody
read-initial
(setf c (read-char stream nil))
(cond
((whitespace-or-nil-p c) (peek-char t stream nil) (go read-initial))
((not (alphanumericp c)) (go skip-til-next))
((digit-char-p c) (go read-number))
((alpha-char-p c) (go read-simple-or-contracted-word))
(t (return-from read-word))
)
skip-til-next
(get-output-stream-string out)
(loop until (whitespace-or-nil-p (peek-char nil stream nil)) do (read-char stream nil))
(go read-initial)
read-number
(write-char c out)
(setf c (read-char stream nil))
(cond
((whitespace-or-nil-p c)
(return-from read-word (get-output-stream-string out)))
((not (digit-char-p c)) (go skip-til-next))
(t (go read-number))
)
read-simple-or-contracted-word
(write-char c out)
(setf c (read-char stream nil))
(cond
((whitespace-or-nil-p c)
(return-from read-word (get-output-stream-string out)))
((and (char/= c #\') (not (alpha-char-p c))) (go skip-til-next))
(t (go read-simple-or-contracted-word))
)
))))
【问题讨论】:
标签: lisp common-lisp infinite-loop word