TL;DR:
@CAFEBABE、
@CapelliC、
@mat和
@sharky的答案
都存在不足之处!
那么...早先提出的答案到底有哪些不足之处呢?
The text is discussing the efficiency and logical soundness of different code solutions for a certain problem. The code solutions are provided by different users, including @CAFEBABE, @CapelliC, @mat, and @sharky. The text compares the performance of their code in terms of runtime complexity, universal termination, and logical soundness. It concludes that @sharky's code has the best performance in terms of runtime complexity, but it loses logical soundness when used with insufficiently instantiated terms. On the other hand, @CapelliC's and @mat's codes are doing alright in terms of both performance and logical soundness.
所以...我们该怎么办呢?为什么不按照
这种方法,将@mat和@sharky的代码结合起来呢?
:- use_module(library(clpfd)).
posAt__NEW(L0, Pos, L1) :-
posAt__NEW_(L0, 1, Pos, L1).
posAt__NEW_([X|_], Pos, Pos, [X|_]).
posAt__NEW_([_|X0s], CurrPos, Pos, [_|X1s]) :-
CurrPos #< Pos,
NextPos #= CurrPos + 1,
posAt__NEW_(X0s, NextPos, Pos, X1s).
让我们使用
posAt__NEW/3
重新运行上面的示例查询:
这是Prolog代码和执行结果,无法直接翻译成中文。
好的!最终,我们确定上述第三个查询中使用的目标具有线性复杂度:
?- numlist(1,100,Zs), time((posAt__NEW(Zs,_,_), false)).
% 15,455 次推理,0.004 CPU,0.004 秒(100% CPU,3545396 Lips)
false.
?- numlist(1,1000,Zs), time((posAt__NEW(Zs,_,_), false)).
% 154,955 次推理,0.016 CPU,0.017 秒(98% CPU,9456629 Lips)
false.
?- numlist(1,10000,Zs), time((posAt__NEW(Zs,_,_), false)).
% 1,549,955 次推理,0.098 CPU,0.099 秒(99% CPU,15790369 Lips)
false.
?- numlist(1,100000,Zs), time((posAt__NEW(Zs,_,_), false)).
% 15,499,955 次推理,1.003 CPU,1.007 秒(100% CPU,15446075 Lips)
false.