我在一个名为test.pl
的文件中定义了一个名为length
的过程:
% Finds the length of a list.
length([], 0).
length([_ | Tail], N) :-
length(Tail, N1),
N is 1 + N1.
当程序使用 SWI-Prolog (prolog test.pl
( 运行时,会出现以下错误:
ERROR: /home/user/test.pl:2:
No permission to modify static procedure `length/2'
Defined at /usr/lib/swi-prolog/boot/init.pl:3496
ERROR: /home/user/test.pl:3:
No permission to modify static procedure `length/2'
Defined at /usr/lib/swi-prolog/boot/init.pl:3496
我尝试将过程的名称从length
更改为mylength
,但错误消失了。此错误是什么意思?我可以定义一个名为length
的过程吗?如果没有,为什么不能做到?
length/2 没有在 Prolog 中定义,但它是原生(高效(列表实现上的浅层接口的一部分。您应该使用指令redefine_system_predicate。
例如,保存在文件中redef_length.pl
:- redefine_system_predicate(length(?,?)).
% Finds the length of a list.
length([], 0).
length([_ | Tail], N) :-
length(Tail, N1),
N is 1 + N1.
然后咨询它
?- [test/prolog/redef_length].
true.
?- trace.
true.
[trace] ?- length(A,B).
Call: (8) length(_1476, _1478) ? creep
Exit: (8) length([], 0) ? creep
A = [],
B = 0 ;
Redo: (8) length(_1476, _1478) ? creep
Call: (9) length(_1718, _1738) ? creep
Exit: (9) length([], 0) ? creep
Call: (9) _1478 is 1+0 ? creep
Exit: (9) 1 is 1+0 ? creep
Exit: (8) length([_1716], 1) ? creep
A = [_1716],
B = 1
没错。length/2
是一个内置谓词:length(?列表?Int( 为 True,如果Int表示List中的元素数。所以这个名字已经被使用了。