(1)
% occurrences(Sub,Term,N) :-
% 項Term中の部分項Subの出現回数がNのとき真になる.
occurrences(Term,Term,1) :- !.
occurrences(Sub,Term,N) :-
compound(Term), !,
functor(Term,F,M), occurrences(M,Sub,Term,0,N).
occurrences(Sub,Term,0).
occurrences(M,Sub,Term,N1,N2) :-
M > 0, !, arg(M,Term,Arg), occurrences(Sub,Arg,N),
N3 is N+N1, M1 is M-1, occurrences(M1,Sub,Term,N3,N2).
occurrences(0,Sub,Term,N,N).
(2)
% position(Subterm,Term,Position) :-
% Positionは項Term中の部分項Subtermが占める
% 引数位置のリストである.
position(Term,Term,[]) :- !.
position(Sub,Term,Path) :-
compound(Term), functor(Term,F,N),
position(N,Sub,Term,Path), !.
position(N,Sub,Term,[N|Path]) :-
arg(N,Term,Arg), position(Sub,Arg,Path).
position(N,Sub,Term,Path) :-
N > 1, N1 is N-1, position(N1,Sub,Term,Path).
(3)
% univ(Term,List) :-
% Listは,Termの関数子と,その後ろに
% Termの引数を連ねたものからなるリストである.
univ(Term,[F|Args]) :-
functor(Term,F,N), args(N,Term,Args,[]).
args(N,Term,Xs,Ys) :-
N > 0, N1 is N-1,
arg(N,Term,Arg), args(N1,Term,Xs,[Arg|Ys]).
args(0,Term,Xs,Xs).
(4)
% functor1(Term,F,Arity) :-
% Termは,主関数子の名前がFで
% 引数の数がArityであるような項である.
functor1(Term,F,N) :-
Term =.. [F|Args], length(Args,N).
% arg1(N,Term,Arg) :-
% Argは,項TermのN番目の引数である.
arg1(N,Term,Arg) :-
Term =.. [F|Args], retrieve(N,Args,Arg).
retrieve(1,[X|Xs],X).
retrieve(N,[X|Xs],Y) :-
N > 1, N1 is N-1, retrieve(N1,Xs,Y).
(5)
% substitute(Old,New,OldTerm,NewTerm) :-
% NewTermは,OldTerm中のOldをNewに置き換えたものである.
substitute(Old,New,Old,New).
substitute(Old,New,Term,Term) :-
atomic(Term), Term \= Old.
substitute(Old,New,Term,Term1) :-
compound(Term),
Term =.. [F|Args],
substitute_args(Old,New,Args,Args1),
Term1 =.. [F|Args1].
substitute_args(Old,New,[Arg|Args],[Arg1|Args1]) :-
substitute(Old,New,Arg,Arg1),
substitute_args(Old,New,Args,Args1).
substitute_args(Old,New,[],[]).
0 件のコメント:
コメントを投稿