计算谓词中列表的元素

Counting elements of a list in a predicate

我有这样的东西:

plane(1, 2, aaa, b([1,2,3,4]), 3).

我可以像上面一样访问平面的元素并显示它,但问题是 b([1,2,3,4])。 我怎样才能访问它来计算该列表中元素的数量?

如果这些plane的格式总是相同的,那么你可以通过模式匹配(统一)将b中的列表绑定到一个变量,然后检查长度(用法count_in_plane(+,-),即提供P,得到L):

count_in_plane(P, L) :- 
    P = plane(_,_,_, b(List), _),
    length(List, L).

假设您已将参数编号 4 与变量 B_list 统一。如果您想从其中获取列表,请使用统一运算符 =,如下所示:

/* Let's pretend that you do not need other parameters */
plane(_, _, _, B_list, _) :-
    /* This assigns the content of the list inside b(...) to List */
    B_list = b(List),
    length(List, N),
    write(N),
    nl.

这将打印 4。

简单点,比如:

count( plane(_,_,_, b(List), _), R ) :- length(List, R).