我有几个谓词使用 lambda 、来自 func 的波浪号、lambda 和 func 做同样的事情,最后是既没有 lambda 也没有 func 的“纯 Prolog”:
:- use_module(library(lambda)).
:- use_module(library(func)).
both_lambda_and_func :-
maplist(\X^(print(length(X,~))), [`one`,`two`,`three`]).
lambda_only :-
maplist(\X^(length(X,Len),print(Len)), [`one`,`two`,`three`]).
func_only :-
maplist(func_only_helper, [`one`,`two`,`three`]).
func_only_helper(X) :-
print(length(X,~)).
normal_prolog :-
maplist(normal_prolog_helper, [`one`,`two`,`three`]).
normal_prolog_helper(X) :-
length(X,Len),
print(Len).
所有谓词都应该打印
335
(列表中字符串的长度)并且其中三个正确执行。问题是 both_lambda_and_func/0
不打印任何内容,似乎进入了无限循环。我试过 trace/0
问题,但对我来说似乎太复杂了。你能告诉我是我做错了什么还是这是一些奇怪的错误?我正在使用 SWI-Prolog 7.1.14、func 0.0.4、lambda 1.0.0。 最佳答案
?- listing(both_lambda_and_func).
both_lambda_and_func :-
length(A, B),
maplist(\A^print(B),
[[111, 110, 101], [116, 119, 111], [116, 104, 114, 101, 101]]).
不可能在错误的上下文中表达 ~ 术语的范围,即盲目改写。程序不会终止,因为 length/2 的两个参数都是空闲的,然后生成更长的列表。
[trace] 4 ?- both_lambda_and_func.
Call: (6) both_lambda_and_func
Call: (7) length(_G1485, _G1486)
Exit: (7) length([], 0)
^ Call: (7) apply:maplist(\[]^print(0), [[111, 110, 101], [116, 119, 111], [116, 104, 114, 101|...]])
Call: (8) apply:maplist_([[111, 110, 101], [116, 119, 111], [116, 104, 114, 101|...]], user: \[]^print(0))
^ Call: (9) lambda: \([]^print(0), [111, 110, 101])
Call: (10) copy_term_nat(user:[]^print(0), _G1541)
Exit: (10) copy_term_nat(user:[]^print(0), user:[]^print(0))
^ Call: (10) lambda: ^([], print(0), [111, 110, 101])
^ Fail: (10) lambda: ^([], user:print(0), [111, 110, 101])
^ Fail: (9) lambda: \(user:[]^print(0), [111, 110, 101])
Fail: (8) apply:maplist_([[111, 110, 101], [116, 119, 111], [116, 104, 114, 101|...]], user: \[]^print(0))
^ Fail: (7) apply:maplist(user: \[]^print(0), [[111, 110, 101], [116, 119, 111], [116, 104, 114, 101|...]])
Redo: (7) length(_G1485, _G1486)
Exit: (7) length([_G1478], 1)
^ Call: (7) apply:maplist(\[_G1478]^print(1), [[111, 110, 101], [116, 119, 111], [116, 104, 114, 101|...]])
Call: (8) apply:maplist_([[111, 110, 101], [116, 119, 111], [116, 104, 114, 101|...]], user: \[_G1478]^print(1))
^ Call: (9) lambda: \([_G1478]^print(1), [111, 110, 101])
Call: (10) copy_term_nat(user:[_G1478]^print(1), _G1547)
Exit: (10) copy_term_nat(user:[_G1478]^print(1), user:[_G1546]^print(1))
^ Call: (10) lambda: ^([_G1546], print(1), [111, 110, 101])
^ Fail: (10) lambda: ^([_G1546], user:print(1), [111, 110, 101])
...
对 ^ 的调用出错
^ Fail: (10) lambda: ^([], user:print(0), [111, 110, 101])
因为X它已经实例化为[],而应该是免费的......
关于lambda - 为什么在使用带有 lambda 和波浪号项的 maplist 时会出现无限循环?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23554562/