Search code examples
prolog

How to Add all lengths of sublists In prolog . Please Help me , i'm stuck


Adding all lengths of sublists In prolog Using

sum([],ADD,ADD).
sum([P|R], ADD, OUTPUT):- X is ADD + P,
                          sum(R,X,ADD).

Solution

  • 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.