Prolog 获取用户输入的字符串,避免输入错误时程序终止
我正在尝试在 prolog 中编写一个简单的 shell。 我目前使用 read/1 查询用户输入。
但是我有两个问题想解决。
1) 用户只能输入条款。
该查询要求用户输入一个术语并要求输入以句点结尾。 这是限制,因为我希望用户能够输入诸如“将变量设置为值”之类的命令(我将解析该字符串)。有什么方法可以在序言中读取这些字符串吗? (如果可能的话,没有任何开销,例如列表表示、引号或结束句点?)
2)如果用户输入不正确的内容(例如空格),我会收到语法错误并且 shell 结束。 什么是快速且正确的方法来处理这些错误并避免程序终止?
非常感谢所有帮助!
I'm trying to write a simple shell in prolog.
I currently query the user for input using read/1.
However I have two issues I would like to resolve.
1) user can only enter terms.
the query requires the user to enter a term and requires the input to end with a period.
This is to restricting as I wish the user to be able to enter commands like 'set Variable to Value' (I will parse this string). Is there any way to read such strings in prolog? (if possible without any overhead, such as list respresentation, quotes or an ending period?)
2) if the user enters something incorrect (such as a space), I get a syntax error and the shell ends.
What is a quick and proper way to handle these errors and avoid program termination?
All help is most appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好的“工具”:DCG。例如,使用 SWI-Prolog:
The best 'tool' available: DCG. For instance, using SWI-Prolog:
读取输入不限于术语,还可以通过
get_char/1
和get_byte/1
以每个字符或每个字节为基础执行。不完全引人注目,甚至不那么容易合作。例如,您可以看一下 来自Prolog 的艺术的小片段,其中作者定义了一个谓词来从标准输入中读取单词列表(缺少一些特定过程的定义,即读者可根据需要提供)。Prolog 通过
catch/3
支持错误处理,您可以使用它来捕获读取操作期间出现的错误并做出正确的反应。Reading input is not restricted to terms, but can be performed on a per character or per byte basis by means of
get_char/1
andget_byte/1
. Not exactly compelling, not even that easy to work with. As an example, you may take a look at a small snippet from The Art of Prolog where the authors define a predicate to read a list of words from standard input (definitions for some specific procedures are missing, i.e. to be provided by the reader on the basis of his needs).Prolog supports error handling by means of
catch/3
, which you may use to catch errors sprouted during the reading operations and react properly.