在 prolog 中检查对象是否是二叉树

问题描述 投票:0回答:1

prolog 有一个任务听起来像这样: 编写一个 istree 谓词,仅当其参数是二叉树时才返回 true。 示例:

?- istree(t(a,t(b,nil,nil),nil)).
返回是

?- istree(t(a,t(b,nil,nil))).
返回否

我尝试编写自己的代码并停在这个版本:

domains
tree = nil; t(symbol, tree, tree).

predicates
istree(tree).
isleaf(tree).

clauses
istree(nil).
istree(t(_, Left, Right)) :-
istree(Left),
istree(Right).
isleaf(t(_, nil, nil)).

goal
%istree(t(a, t(b, nil, nil), nil)).
istree(t(a, t(b, nil, nil))).

现在,当我尝试输入示例中的第二行(

istree(t(a, t(b, nil, nil))).
)时,我收到错误:
E;Test_Goal, pos: 246, 507 Type error: Wrong number of arguments

我该如何修复它?

prolog binary-tree
1个回答
0
投票

您正在使用 prolog 语言的强类型扩展。所以定义:

domains 
    tree = nil ; 
           t(symbol, tree, tree).

保证只能创建二叉树。为了避免编译错误,您应该relax定义,例如:

domains tree = nil ; t(symbol, tree, tree) ; t(symbol, tree).
这样,并非所有创建的树都是二叉树,因此使用一个谓词来检查特定树是否是二叉树是有意义的。

© www.soinside.com 2019 - 2024. All rights reserved.