How do I state that two lists have the same length

2019-07-21 06:14发布

问题:

I need to know how to compare the length of two lists in Prolog. This is what I have so far:

sum(N1,N2) :-
    checklength(N1,N2).

checklength(N1,N2) :-
    L1 is length(N1,What),
    L2 is length(N2,What),
    Comp(L1,L2).

Comp(L1,L2) :-
    L1=:=L2.

回答1:

Of course, the answer from CapelliC is perfect, but you can try also the "standard" method of approaching this problem:

same_length([],[]).
same_length([_|L1],[_|L2]) :- same_length(L1, L2).


回答2:

If you're using SWI-Prolog, then you can simply use same_length/2 predicate.



回答3:

you can use unification:

checklength(N1,N2):-
    length(N1,What),
    length(N2,What).

this will succeed only if N1 and N2 have the same length.

Btw L1 is length(N1,What) doesn't make sense. length/2 is a predicate, not a function. That is, it will succeed or fail, but doesn't 'return' a value. Otoh, is/2 expects an arithmetic expression as right operand.

edit

checklength(N1,N2,R1,R2):-
    length(N1,L1),
    length(N2,L2),
    (   L1 < L2
    ->  lpad(L1,L2,N1,R1), R2 = N2
    ;   L2 < L1
    ->  lpad(L2,L1,N2,R2), R1 = N1
    ;   (R1,R2) = (N1,N2)
    ).

lpad(A,A,L,L) :- !.
lpad(A,B,L,[0|T]) :- A < B, C is A+1, lpad(C,B,L,T).


标签: prolog