Search code examples
prologinstantiation-error

Counting variables during recursion


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!


Solution

  • You are very close. The problem is this line NZ is N + 1 where N has not yet been instantiated, NZ can not possibly wait for the N to be instantiated.

    The solution is to get NZ and then add the 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.