I have declared a type of objects as follows:
type([coffee, tea, lemonade, water, coke, beer]: drink).
How can I get a list of all the objects of type drink
?
You can use unification, like:
type(L : drink).
This will unify L
with that list, like:
?- type(L: drink).
L = [coffee, tea, lemonade, water, coke, beer].
That being said, it is not very common to use a colon (:
) here, usually one uses different parameters. Furthermore lists are not very common in facts either, since you hereby lose the ability to easily check what the type of tea
is for example.
It is more idiomatic to write:
type(coffee, drink).
type(tea, drink).
type(lemonade, drink).
type(water, drink).
type(coke, drink).
type(beer, drink).
We can for example query for elements of the type drink
:
?- type(D, drink).
D = coffee ;
D = tea ;
D = lemonade ;
D = water ;
D = coke ;
D = beer.
Or to query what the type of water
is:
?- type(water, T).
T = drink.
Check if a newspaper
or coke
are drink
s:
?- type(newspaper, drink).
false.
?- type(coke, drink).
true.
and enumerate over all items with their type:
?- type(X, T).
X = coffee,
T = drink ;
X = tea,
T = drink ;
X = lemonade,
T = drink ;
X = water,
T = drink ;
X = coke,
T = drink ;
X = beer,
T = drink.
You can then create a list with the findall/3
[swi-doc] predicate:
?- findall(D, type(D, drink), Ds).
Ds = [coffee, tea, lemonade, water, coke, beer].