我的目标是返回列表列表中最长的列表。例如:[[1,2,3],[1,2]]-> [1,2,3]。
这是我写的
list_max_len([L],L).
list_max_len([X,Y|T],L):-
length(X) >=length(Y),
list_max_len([X|T],L).
list_max_len([X,Y|T],L):-
length(X) < length(Y),
list_max_len([Y|T],L).
但是我收到了这个错误:
谁能解释一下这是什么?
目前还不清楚您正在使用什么 Prolog 实现。但是,
length/1
不是计算列表长度的谓词。标准/ISO 谓词是 length/2
。
尝试这样的事情(假设您可以使用内置的
length/2
:
list_max_len( [L|Ls] , N ) :- % To figure out the length of the longest list in a list-of-lists,
length(L,M) , % - compute the length of the 1st list, and
list_max_len(Ls,M,N). % - examine the remainder, seeding the current max
. % Easy!
list_max_len( [L|Ls] , M , N ) :- % to compute the length of the longest list in a list-of-lists....
length(L,X) , % - get the length of the head
M1 is max(M,X), % - pick the larger of the current max and the length of the head
list_max_len(Ls,M1,N) % - recurse down
. % Easy!
.