Prolog length of a list

前端 未结 2 1838
星月不相逢
星月不相逢 2021-01-21 07:51

How can I calculate the length of a list

?- size_sub([[b,a,g], [9,3,7,4], [6]],  X).
X = [3, 4, 1].

?- size_sub([[c,g,e,w], [7]],  X).
X = [4, 1].

?- size_sub(         


        
相关标签:
2条回答
  • 2021-01-21 08:31

    To map length/2 over a list of lists, we can use the meta-predicate maplist/3 like this:

    size_sub(Xss,Ls):-
        maplist(length,Xss,Ls).
    
    0 讨论(0)
  • 2021-01-21 08:44

    Ok you need to start with the base case which is the last answer

    so size_sub([],X). is true if X=[] so first you write that as a rule.

    size_sub([],[]).
    

    Then you need to do the inductive step a list that is one longer than the previous. I am going to assume that you have a size/2 function for determining the size of a single list (if not please comment).

    So the inductive step is going to operate on the length of the first parameter so N->N+1. We would represent this by striping off the head of the list syntax will be [H|T] now the second parameter (your answer) is going to be the length of H with the result of calling size_sub on T. As we cannot specify rules in the parameters in the header we will use N to represent the length of H and T2 to represent the result of size_sub on T.

    So the first part of the rule becomes size_sub([H|T],[N|T2]):-

    now we follow it with the predicates that will assert the values for N and T2.

    size(H,N),
    size_sub(T,T2).
    

    putting that all together you get

    size_sub([],[]).
    
    size_sub([H|T],[N|T2]):-
        size(H,N),
        size_sub(T,T2).
    

    size/2 is a far simpler case and following the same process of base + inductive you should be able to create the rules for it. Please comment if you need further help.

    ** EDIT - Request for size/2 definition **

    To define size/2

    Start with the base case, the empty list has a size of 0.

    size([],0).
    

    Now the inductive step. The size of list of length(N+1) is the size of a list of length(N). So lets define our list as [_|T] I've defined the list using _ to represent the head because we never use it so we can just use the anonymous variable. Lets use N to represent the length of T, and M to be N+1.

    so

    size([_|T],M):-

    now lets define N

      size(T,N),
    

    and finally assert that M is equal to N + 1

      M is N+1.
    

    so putting everything together

    size([],0).
    
    size([_|T],N):-
        size(T,M),
        N is M+1.
    
    size_sub([],[]).
    
    size_sub([H|T],[N|T2]):-
        size(H,N),
        size_sub(T,T2).
    
    0 讨论(0)
提交回复
热议问题