Carles Araguz
Carles Araguz

Reputation: 1177

How to generate a list of activable tasks in Prolog?

I'm programming a task scheduler in Prolog. I have a set of predicates that define when a task can be considered activable, like this:

task(id01).
task(id02).
task(id03).
task(id04).

activable(X) :-
    task(X),
    inactive(X),
    conditions1(X).
activable(X) :-
    task(X),
    inactive(X)
    conditions2(X).
activable(X) :-
    task(X),
    inactive(X),
    conditions3(X).

I wonder how may I generate a list of all activable tasks, before activating any of them. I tried with something like this:

handle_activable([A|As]) :-
    activable(A),
    handle_activable(As).
handle_activable([]).

schedule :-
    handle_activable(As),
    activate_all(As).

But when I call schedule/0, I always get the first task checked, task(id01), and the first activable/1 clause goals constantly. I know it's silly but I can't find how to get a list of activable tasks. Even simpler, how to generate a list of tasks...?

Upvotes: 2

Views: 262

Answers (1)

CapelliC
CapelliC

Reputation: 60004

Prolog has a particular execution flow. Alternatives are considered on backtracking. Then you need to use some builtin that internally use backtracking, like findall does, or a failure driven loop like forall, if you are interested in generating side effects for each solution you can find.

Bottom line:

schedule :-
    findall(A, activable(A), As),
    activate_all(As).

or

schedule :-
    forall(activable(A), activate(A)).

where activate/1 implements the side effect

Upvotes: 4

Related Questions