在大学学习后,我正在重新访问 Prolog,并想描述一个包含函数类型的类型层次结构。到目前为止,这就是我得到的(SWISH 链接):
% subtype/2 is true if the first argument is a direct subtype of
% the second.
subtype(bit, byte).
subtype(byte, uint16).
subtype(uint16, uint32).
subtype(uint32, uint64).
subtype(uint64, int).
subtype(int8, int16).
subtype(int16, int32).
subtype(int32, int64).
subtype(int64, int).
% isa/2 checks if there's a sequence of types that takes
% from X to Y.
isa(X,Y) :- subtype(X,Y).
isa(X,Y) :-
subtype(X,Z),
isa(Z,Y).
该程序适用于以下查询:
?- subtype(bit, int).
true
?- findall(X,isa(X,int),IntTypes).
IntTypes = [uint64, int64, bit, byte, uint16, uint32, int8, int16, int32]
然后我为上面的函数子类型添加了以下定义isa
,其中函数是一个复杂的术语func(ArgsTypeList, ResultType)
:
% Functions are covariant on the return type, and
% contravariant on the arguments' type.
subtype(func(Args,R1), func(Args,R2)) :-
subtype(R1, R2).
subtype(func([H1|T],R), func([H2|T],R)) :-
subtype(H2, H1).
subtype(func([H|T1],R), func([H|T2],R)) :-
subtype(func(T1,R), func(T2,R)).
现在,我仍然可以进行一些有限检查,但即使尝试枚举所有子类型的byte
堆栈溢出失败。
?- isa(func([int,int], bit), func([bit,bit], int)).
true
?- isa(X, byte).
X = bit ;
Stack limit (0.2Gb) exceeded
我究竟做错了什么?