【发布时间】:2020-01-22 08:55:41
【问题描述】:
据我所知,Prolog 没有任何用于generic programming 的内置机制。可以使用统一来模拟泛型,但这需要在运行时进行类型检查:
:- 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).
是否可以编写“通用”谓词而不在运行时检查每个变量的类型?
【问题讨论】:
-
Prolog 是动态类型的。所以没有太多的类型检查,就像在 Python 中一样。
-
这有点像问如何模拟自动变速器汽车的离合器。 “通用编程”本身仅适用于具有静态类型检查的语言。每个 Prolog 谓词就其接受的类型而言已经是通用的,并且除了运行时之外,Prolog 中没有其他类型的类型检查。在 Python 和其他所有动态类型语言中,情况都是一样的。 Python 的“类型系统”在设计上对 Python 程序的语义或其评估没有任何影响。
-
一个小评论:在你的情况下有意义的类型不包括
var。请参阅this 了解更多信息。
标签: generics prolog polymorphism parametric-polymorphism