So, I am very new to Prolog and I have to write a short code about timetable. How can I add the findall function to a code itself?
happening(monday,chemistry).
happening(monday,english).
happening(tuesday,chemistry).
happening(wednesday,maths).
happening(friday,chemistry).
happening(friday,maths).
And now I want to write a command that shows how many times do I have chemistry in a week.
find_lessons(X) :-
findall(X,happening(X,chemistry), Bag).
I assume you want the result, so the
Bag
, so you should rewritefind_lessons(X)
tofind_lessons(Bag)
:This will then give a list of days when there is a chemistry lesson, so:
to count the number of lessons, you can use
length/2
:But one can do this more efficient. Right now there is overhead in constructing the list, and counting the elements. We can make use of the
aggregate
library [swi-doc] and use theaggregate/3
predicate [swi-doc]:so we can count the number of chemistry lessons with: