简体   繁体   中英

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?

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].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM