Search code examples
recursionprologmutual-recursion

Prolog Mutual recursion


Ok I'm writing some code to go through a check each value by mutual recursion in Prolog. This is my code so far:

semestersok(SP) :-
    [Prior|Tail] = SP,
    sem1ok(SP).



%% sem1ok(SP) :- checks semester 1 of SP is ok
sem1ok(SP) :-
    [Sem1|Tail] = SP,
    sem2ok(Tail).

%% sem2ok(SP) :-
sem2ok(SP) :-
    [Sem2|Tail] = SP,
    sem1ok(Tail).

I haven't put any code in yet to do with checking (There's two relations as it has to check alternating values), I'm having a problem with the code cycling through until it has an empty list, then it fails and comes back with false (no). Since This code isn't manipulating any code I believe it should come back true as it stands right now. Why isn't it?


Solution

  • You need some rules for the empty list. Add this:

    sem1ok([]).
    sem2ok([]).
    

    Also, the code might be more intuitive if you write it like this (as the distinction between the rule matching the empty list and the one matching the non-empty list is more clear):

    % Rules for sem1ok/1
    sem1ok([]).
    sem1ok([Sem1|Tail]):-
        ok(Sem1), % Something involving Sem1
        sem2ok(Tail).
    
    % Rules for sem2ok/1
    sem2ok([]).
    sem2ok([Sem2|Tail]):-
        ok(Sem2), % Something involving Sem2
        sem1ok(Tail).