1

I want to create a program, which should determine the differences between two lists with equal length and give out the number of differences in a variable. My code so far is:

difference([],[],0).
difference(L1,L2,N) :- 
    L1=[H1|T1], 
    L2=[H2|T2], 
    H1=H2, 
    difference(T1,T2,N).
difference(L1,L2,N) :- 
    L1=[H1|T1],
    L2=[H2|T2],
    H1\=H2,
    NZ is N + 1,
    difference(T1,T2,NZ).

The program works for two identical lists, but it doesn't count the differences between to lists, for example "difference([1,2,3],[1,2,4],N)" gives me the error "Arguments are not sufficiently instantiated". How to fix this?

Thanks in advance!

4

1 回答 1

3

你很亲密。问题是这条线还没有被实例化,NZ is N + 1不可能等待被实例化。NNZN

解决方案是获取 NZ,然后添加1.

difference([],[],0).
difference(L1,L2,N) :- 
    L1=[H1|T1], 
    L2=[H2|T2], 
    H1=H2, 
    difference(T1,T2,N).
difference(L1,L2,N) :- 
    L1=[H1|T1],
    L2=[H2|T2],
    H1\=H2,
    difference(T1,T2,NZ),
    N is NZ + 1.
于 2016-11-23T15:24:23.900 回答