0

Adding all lengths of sublists In prolog Using

sum([],ADD,ADD).
sum([P|R], ADD, OUTPUT):- X is ADD + P,
                          sum(R,X,ADD).
false
  • 10,264
  • 13
  • 101
  • 209
kid eruU
  • 3
  • 1
  • your code seems to add a list of numbers (like calling `sumlist(List, Sum)` ). If you have a list of lists and want to add the length of each list then call `length(P, LP)` at the beginning of the second clause and then use `LP` instead of `P` – gusbro May 26 '22 at 19:03

2 Answers2

1

Avoiding the slow recursion:

sublists_len(SubLists, Length) :-
    sublists_len_(SubLists, 0, Length).
    
sublists_len_([], Len, Len).
sublists_len_([H|T], Upto, Len) :-
    length(H, LenH),
    Upto1 is Upto + LenH,
    sublists_len_(T, Upto1, Len).

Performance comparison in swi-prolog:

?- length(SubLists, 5000000), maplist(=([1, 2]), SubLists), time(sublists_len(SubLists, Len)).
% 20,000,002 inferences, 2.730 CPU in 2.697 seconds (101% CPU, 7326281 Lips)

?- length(SubLists, 5000000), maplist(=([1, 2]), SubLists), time(list_subsum(SubLists, Len)).
% 20,000,001 inferences, 7.581 CPU in 7.500 seconds (101% CPU, 2638194 Lips)
brebs
  • 3,462
  • 2
  • 3
  • 12
0
nestedlist_length(List, Length) :-
    flatten(List, Flat),
    length(Flat, Length).

Your code: sum([],ADD,ADD). says that the sum of the lengths of an empty list could be anything, as long as you repeat it enough. sum([], 50, 50). works there, so does sum([], dog, dog)..

This: sum([P|R], ADD, OUTPUT):- X is ADD + P, sum(R,X,ADD). says that you never use OUTPUT again, and that you try and add the head onto nothing and then stuff that down into the sum of the tail which can never get a value because there's nowhere that you say an empty list has length sum of 0.

list_subsum([], 0).
list_subsum([H|T], Output) :-
    length(H, HLen),
    list_subsum(T, TLengthSum),
    Output is HLen + TLengthSum.

Empty lists are length 0, lists of things get the length of the head, get the length of the tail, then output those two added together.

The tail will eventually be [] which will have a length 0 which stops the process.

TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87