gpt4 book ai didi

list - Prolog 错误参数

转载 作者:行者123 更新时间:2023-12-04 15:32:51 24 4
gpt4 key购买 nike

我想知道如何在 Prolog 中添加错误检查。
例如,我有一个程序可以查找列表的长度:

listlen([],0). 
listlen([_|T],N) :-
listlen(T,X),
N is X+1.

当它发生时,我如何打印出“第一个参数必须是列表”之类的错误?

最佳答案

SWI-Prolog 有 ISO-compliant exception handling ,所以你实际上可以抛出错误 as defined in the standard .

?- throw(error(type_error(list, foo), context(foo/0, 'Must be a list'))).
ERROR: foo/0: Type error: `list' expected, found `foo' (an atom) (Must be a list)
这不仅难以输入/使用:它还依赖于实现。相反,您可以(并且应该)使用 library(error) ,它提供了 must_be/2 predicate (遗憾的是,如果您不知道要查找什么,则很难在 SWI-Prolog 网站上找到它):
?- must_be(list, [foo]).
true.

?- must_be(list, foo).
ERROR: Type error: `list' expected, found `foo' (an atom)
我假设其他支持异常处理的 Prolog 实现提供了非常相似的功能。

关于list - Prolog 错误参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33685244/

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