prolog中的这个或那个事实
我想在prolog中构建一个费用计算器。可以显示事实prolog中的这个或那个事实,prolog,Prolog,我想在prolog中构建一个费用计算器。可以显示事实一次性费用(X)。或每月费用(X)。。为了计算费用,我使用以下公式: expenses(X):- findall( Value, ( monthly_expense(Y), Value is Y * 12 ), Values ), findall( Value1, ( onetime_expen
一次性费用(X)。
或每月费用(X)。
。为了计算费用,我使用以下公式:
expenses(X):-
findall(
Value,
( monthly_expense(Y),
Value is Y * 12
),
Values
),
findall(
Value1,
( onetime_expense(Z),
Value1 is Z
),
Values1
),
sum_list(Values, Sum),
sum_list(Values1, Sum1),
X is Sum + Sum1.
不幸的是,如果其中一个事实不在知识库中,prolog会抛出错误“UndefinedProcedure”。如何解决这个问题?一个简单的解决方案是将谓词声明为动态的:
:- dynamic(monthly_expense/1).
:- dynamic(onetime_expense/1).
对声明为动态但未定义的谓词的调用将失败,而不是抛出谓词存在错误
另外,您可以使用事实上的标准谓词findall/4
简化代码:
expenses(Sum):-
findall(
MonthlyValue,
( monthly_expense(Y),
MonthlyValue is Y * 12
),
MonthlyValues
),
findall(
OneTimeValue,
( onetime_expense(Z),
OneTimeValue is Z
),
Values,
MonthlyValues
),
sum_list(Values, Sum).
我觉得出现这个问题会很奇怪,而且最终不会遇到缺少的
动态声明。您可以简单地说:findall(Value1,(onetime_-expense(Z),Value1是Z),Values1),
-->findall(Value1,onetime_-expense(Value1),值1),