如何从Prolog中的术语中获取原子变量列表 [英] How to get list of atom variables from a term in Prolog

查看:39
本文介绍了如何从Prolog中的术语中获取原子变量列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从术语中获取原子变量列表

例如-

Term = (h-5)* (h-5)+ (k- -2)* (k- -2)- (h-3)* (h-3)- (k-4)* (k-4)=0,get_variables(Term, Var_list).

对于上述术语,答案是Var_list = [h,k].

解决方案

以下代码在 SICStus Prolog 4.5.0 和 SWI-Prolog 8.0.0 上运行.

它基于 library(条款)iwhen/2:

:- use_module(library(terms)).atom_in(As, T) :-( \+ acyclic_term(T)->抛出(错误(类型错误(非循环项,T),_));iwhen(ground(T), setof(A, (sub_term(A,T),atom(A)), As))->真的;作为 = []).

使用 SWI-Prolog 8.0.0:

?- atom_in(Xs, (h-5)*(h-5)+(k- -2)*(k- -2)-(h-3)*(h-3)-(k-4)*(k-4)=0).Xs = [h, k].?- atom_in(Xs, f(g(a,b),h(c,d))).Xs = [a, b, c, d].?- atom_in(Xs, f(g(1,2),3)).Xs = [].?- atom_in(Xs, 1).Xs = [].

注意如何捕获和报告无效使用:

<预>?- atom_in(_, _).错误:参数未充分实例化?- atom_in(_, f(_)).错误:参数未充分实例化?- Term = f(a,Term), atom_in(_, Term).错误:类型错误:预期为acyclic_term",找到@(S_1,[S_1=f(a,S_1)])"(循环)

How to get list of atom variables from a term

For example-

Term = (h-5)* (h-5)+ (k- -2)* (k- -2)- (h-3)* (h-3)- (k-4)* (k-4)=0,
get_variables(Term, Var_list).

For above term, the answer would be Var_list = [h,k].

解决方案

The following code runs with both SICStus Prolog 4.5.0 and SWI-Prolog 8.0.0.

It is based on library(terms) and iwhen/2:

:- use_module(library(terms)).

atoms_in(As, T) :-
   (  \+ acyclic_term(T)
   -> throw(error(type_error(acyclic_term, T), _))
   ;  iwhen(ground(T), setof(A, (sub_term(A,T),atom(A)), As))
   -> true
   ;  As = []
   ).

Using SWI-Prolog 8.0.0:

?- atoms_in(Xs, (h-5)*(h-5)+(k- -2)*(k- -2)-(h-3)*(h-3)-(k-4)*(k-4)=0).
Xs = [h, k].

?- atoms_in(Xs, f(g(a,b),h(c,d))).
Xs = [a, b, c, d].

?- atoms_in(Xs, f(g(1,2),3)).
Xs = [].

?- atoms_in(Xs, 1).
Xs = [].

Note how invalid uses are caught and reported:

?- atoms_in(_, _).
ERROR: Arguments are not sufficiently instantiated

?- atoms_in(_, f(_)).
ERROR: Arguments are not sufficiently instantiated

?- Term = f(a,Term), atoms_in(_, Term).
ERROR: Type error: `acyclic_term' expected, found `@(S_1,[S_1=f(a,S_1)])' (a cyclic)

这篇关于如何从Prolog中的术语中获取原子变量列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆