我一直在阅读GNU Prolog文档,以了解如何读取一行输入,直到end_of_file
达到一个原子。这是我编写这样一个目标的伪代码:
read_until_end(Chars, Out):
if peek_char unifies with end_of_file, Out = Chars
otherwise, get the current character, add it to a buffer, and keep reading
我是这样实现的:
read_until_end(Chars, Out) :-
peek_char(end_of_file) -> Out = Chars;
peek_char(C) -> read_until_end([C | Chars], Out).
prompt(Line) :-
write('> '),
read_until_end([], Line).
以下是 REPL 中发生的情况:
| ?- prompt(Line).
> test
Fatal Error: global stack overflow (size: 32768 Kb, reached: 32765 Kb, environment variable used: GLOBALSZ)
C
如果我为 的第二个分支打印出来read_until_end
,我可以看到它peek_char
总是给我相同的字符,'b'
。我认为我需要一种方法来推进某种类型的输入字符索引或类似的东西,但我在文档中找不到这样做的方法。如果我知道一种方法,我可能不得不使用递归来处理这样的指针,因为我不能有任何可变状态,但除此之外,我不知道该怎么做。有人有建议吗?