查找与第一个输入元素配对的列表的长度

Finding the length of a List paired with the first input element

我需要实现一个可以

的谓词
size_sub([[a,a,a],[b,b]],X).
and returns 
[a,3],[b,2]

到目前为止我取得的成就

size_sub(A,Ls):-
maplist(length,A,Ls).
returns 
[3,2]

如何将现有功能修改为 return 值数字对。

你可以向 maplist 传递一个谓词做适当的事情,比如

size_sub(A,Ls):-
    maplist(list_sym_len,A,Ls).
list_sym_len([Sym|Rest], [Sym, Len]) :- length([Sym|Rest], Len).

或使用库 lambda。在 SWI-Prolog 中,您可以使用

?- pack_install(lambda).

安装后,您有时可以shorthand您的定义

:- use_module(library(lambda)).
?- maplist(\[Sym|Rest]^[Sym,Len]^length([Sym|Rest], Len), [[a,a,a],[b,c]],R).
R = [[a, 3], [b, 2]].