MCR
MCR

Reputation: 1643

Lists with Prolog

I'm learning rooPlog and having some trouble with lists. I want to return a list of classes that are prerequisites for a specified class. Here is what I have so far...

prereq(262, 221).
prereq(271, 262).
prereq(331, 271).

prerequisites(A, B) :- not(prereq(A, C)).
prerequisites(A, [C|B]) :- prereq(A, C), prerequisites(C, B).

It works, but appends junk onto the end.

?- prerequisites(331, A).
A = [271, 262, 221|_G327] ;
false.

Upvotes: 3

Views: 363

Answers (1)

CapelliC
CapelliC

Reputation: 60004

Maybe you mean

prerequisites(A, []) :- not(prereq(A, _)).
prerequisites(A, [C|B]) :- prereq(A, C), prerequisites(C, B).

You must be sure there are no cycles in your data for this to work...

Upvotes: 3

Related Questions