alia
alia

Reputation: 1

Store result as a list using prolog

I wanted the result to be stored in a list.

subject(english, 2).
subject(math,2).
subject(science,2).

get_subject(subject, level) :- subject(subject,level) .

when I have this query:

?-get_subject(X,2).

it gives me the output:

X = english;
X = math;
X = science.

but i wanted the output to be list like this: [english, math, science] is it possible to do that in prolog?

Upvotes: 0

Views: 881

Answers (1)

Sergii Dymchenko
Sergii Dymchenko

Reputation: 7209

Yes, just use findall:

?- findall(X, get_subject(X,2), Subjects).

Also your get_subject definition should use capital-cased words for variables:

get_subject(Subject, Level) :- subject(Subject, Level).

What Prolog system do you use so your small-cased code works?

And of course your get_subject doesn't do anything useful, you can delete its definition and just use subject directly:

?- findall(X, subject(X,2), Subjects).
Subjects = [english, math, science].

Upvotes: 3

Related Questions