0
votes

I just started Prolog and for practice I'm trying to compare two lists and see if the first list is greater than the second list by one element. So far I got the base case to work, but for any list with more than one element it loops infinitely. Could anyone explain why this is happening? Any information is appreciated.

Code

one_longer([H],[]).
one_longer([H|T],[H2|T2]) :- one_longer([T],[T2]).
1

1 Answers

1
votes

The clause should be:

one_longer([H|T],[H2|T2]) :- one_longer(T,T2).

As one_longer([T],[T2]) forms a new lists with only one element which results in the observed loop as when the rule is applied again results in continually asking one_longer([[]],[[]]) where as one_longer(T,T2) applies one_longer to the remainders of the two lists.