1

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?

4

1 回答 1

2

您需要一些针对空列表的规则。添加这个:

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

此外,如果您这样编写代码可能会更直观(因为匹配空列表的规则和匹配非空列表的规则之间的区别更清楚):

% 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).
于 2014-06-19T08:46:59.650 回答