How do I state that two lists have the same length

2019-07-21 05:33发布

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.

标签: prolog
3条回答
爷的心禁止访问
2楼-- · 2019-07-21 06:15

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).
查看更多
虎瘦雄心在
3楼-- · 2019-07-21 06:20

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).
查看更多
劳资没心,怎么记你
4楼-- · 2019-07-21 06:28

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

查看更多
登录 后发表回答