在Prolog中查找列表长度有麻烦 [英] Trouble with finding length of list in Prolog

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

问题描述

我无法找到列表的长度.我知道如何处理诸如 [a,b,c,d] [a,b,[],d] 甚至是 [a,[[[]],c,[]] 的长度均为4.我遇到的问题是在这种[a,[b,c],d].有4个元素,但是当我运行我的代码时,它会打印3.它将内部列表 [b,c] 视为一个元素,并且我不确定如何分别对它们进行计数.

I'm having trouble finding the length of a list. I know how to deal with lists such as say [a,b,c,d] or [a,b,[],d] or even [a,[[[]]],c,[]] each of which have a length of 4. The problem I'm having is trying to figure out the length of the list in a case like this [a,[b,c],d]. There are 4 elements, but when I run my code, it'll print 3. It considers the inner list [b,c] as a single element and I'm not sure how to count those separately.

这就是我所拥有的:

% this is the base case
mylen([],0).

% case where element is a single atom like a or []
mylen([_|T],Len) :- atom(_),Len is Len1+1.

% case that *should* deal with sublists [b,c]
mylen([[_|TH]|T],Len) :- mylen(TH,Len1), Len is Len1+1.

% general case
mylen([_|T],Len):- mylen(T,Len1),Len is Len1+1.

我希望我的问题清楚.谢谢!

I hope my question is clear. Thank you!

Ps.我查看了与此相关的其他帖子,但找不到针对此特定问题的任何解决方案.

Ps. I looked at other posts concerning this, but couldn't find any solutions to this specific problem.

推荐答案

您的问题来自以下事实:当列表为非空列表时,需要以特殊方式对其进行处理.例如:

Your problem comes from the fact that you need to treat the head of the list in a special way when it is a non-empty list. So for example:

strangelen([], 0).
strangelen([H|T], Len) :-
    (   H = [_|_] % head is a non-empty list
    ->  strangelen(H, LenH)
    ;   LenH = 1
    ),
    strangelen(T, LenT),
    Len is LenH + LenT.

然后:

?- strangelen([a,b,c,d], Len).
Len = 4.

?- strangelen([a,b,[],d], Len).
Len = 4.

?- strangelen([a,[[[]]],c,[]], Len).
Len = 4.

?- strangelen([a,[b,c],d], Len).
Len = 4.

?- strangelen([[]], Len).
Len = 1.

?- strangelen([[[b,c]]], Len).
Len = 2.

此解决方案不适用于不是适当列表的第一个参数(尝试?-strangelen(List,Len).)

This solution does not work for a first argument that is not a proper list (try ?- strangelen(List, Len).)

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

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