Prolog 列表列表中列表的最大长度

问题描述 投票:0回答:1

我的目标是返回列表列表中最长的列表。例如:[[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
1个回答
0
投票

目前还不清楚您正在使用什么 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!
.

© www.soinside.com 2019 - 2024. All rights reserved.