如何在列表列表中找到最长的列表? [英] How do I find the longest list in a list of lists?

查看:72
本文介绍了如何在列表列表中找到最长的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表,我需要找到其中最长的列表.如果有多个长度相同,则返回的长度相同.谢谢.

I have a list of lists, and I need to find the longest one of them. If there are more than one with the same length it's the same which it returns. Thanks.

推荐答案

这是一个通用谓词,它扫描列表以查找由给定目标定义的单个成员.

Here is a general predicate that scans a list to find a single member defined by a given goal.

select_element(Goal, [Head | Tail], Selected) :-
    select_element(Goal, Tail, Head, Selected).


select_element(_Goal, [], Selected, Selected).

select_element(Goal, [Head | Tail], Current, FinalSelected) :-
    call(Goal, Head, Current, Selected),
    select_element(Goal, Tail, Selected, FinalSelected).

让我们说您定义一个谓词

Lets say you define a predicate

get_bigger_number(N1, N2, N) :-
    N is max(N1, N2).

现在您可以执行:

?- select_element(get_bigger_number, [5, 1, -2, 10, 3.2, 0], Selected).

Selected = 10

因此,您现在要做的就是定义一个谓词get_longer_list(L1, L2, L), 并使用它代替get_bigger_number/3.

So all you need to do now is define a predicate get_longer_list(L1, L2, L), and use it instead of get_bigger_number/3.

当然,使用像select_element/3这样的通用谓词可能不是很有效.例如,您应该尝试避免多次计算同一列表的长度,因为在Prolog中这种计算速度很慢(至少如果以标准方式在Prolog中实现).

Of course, using a general predicate like select_element/3 might not be very efficient. For example, you should try to avoid calculating the length of the same list several times, because this calculation is slow in Prolog (at least if implemented in Prolog in the standard way).

这篇关于如何在列表列表中找到最长的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆