And*_*een 5 generics polymorphism prolog parametric-polymorphism
据我所知,Prolog 没有任何内置的泛型编程机制。可以使用统一来模拟泛型,但这需要在运行时进行类型检查:
:- initialization(main).
:- set_prolog_flag(double_quotes, chars).
% this is a "generic" predicate, where A and B have the same type
add(A,B,C) :-
generic_types([A:Type,B:Type]),
(Type = number,
C is A + B;Type=var,C = A+B).
main :-
add(A,B,C),
add(3,4,D),
writeln(C),
writeln(D).
generic_types([]).
generic_types([A:B|C]) :-
member(B,[var,nonvar,float,rational,number,atom,atomic,compound,callable,ground,acyclic_term]),
call(B,A),
generic_types(C).
has_type(Type,A) :-
call(Type,A).
Run Code Online (Sandbox Code Playgroud)
是否可以在运行时不检查每个变量的类型的情况下编写“通用”谓词?
您可以通过将类型参数显式添加到谓词来模拟参数多态性:
add(int, A, B, C) :-
C is A + B.
add(var, A, B, C) :-
C #= A + B.
?- add(var, 2, 3, 5).
true.
?- add(var, A, 3, 5).
A = 2.
?- add(int, A, 3, 5).
ERROR: Arguments are not sufficiently instantiated
Run Code Online (Sandbox Code Playgroud)