Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

prolog reflection (kind of)

Status
Not open for further replies.

kahleen

Programmer
Sep 4, 2008
164
CH
Hi!

I'm having the following problem. Suppose I have the knowledge base from below:

mom(13, bla, bli).
dad(15, foo).
grandma(18, a, b, c, d, e).
grandpa(19, x, y, z).

Each predicate has some parameters of which only the first is important to identify it. Identifiers are unique (or not, I don't think non-uniqueness will do any harm)

What's the best way to implement a predicate get_term that works like this?

?- get_term(13, X).
X = mom(13, bla, bli)

?- get_term(19, Y).
Y = grandpa(19, x, y, z)

Help will be greatly appreciated, thanks in advance :)
 
There is a way in SWI-Prolog :
Code:
:- dynamic (base/2).

mom(13, bla, bli).
dad(15, foo).
grandma(18, a, b, c, d, e).
grandpa(19, x, y, z).

my_index(Pred) :-
	Pred =.. [_, N | _],
	assert(base(N, Pred)).


init :-
	retractall(base(_,_)),
	my_index(mom(13, bla, bli)),
	my_index(dad(15, foo)),
	my_index(grandma(18, a, b, c, d, e)),
	my_index(grandpa(19, x, y, z)).


get_term(N, X) :-
	init,
	base(N, X).
for example
3 ?- get_term(13, X).
X = mom(13, bla, bli).

4 ?- get_term(19, X).
X = grandpa(19, x, y, z).
 
Thank you very much ...

I'm not quite content yet with the part where I have to call my_index for each fact in the KB, given that the KB has many facts like mom and dad ... I don't know how to iterate through all the facts in the KB and call my_index on each of them ... but your solution is great otherwise :)
 
I modify my code and it is a little bit more usefull I think, you just have to know names and arity of facts :
Code:
:- dynamic (base/2).

mom(13, bla, bli).
dad(15, foo).
dad(16, foo_bis).
grandma(18, a, b, c, d, e).
grandpa(19, x, y, z).

my_index([Name, Arity]) :-
	functor(Pred, Name, Arity),
	forall( call(Pred),
		(   Pred =.. [_, N | _],
		    assert(base(N, Pred)))).


init :-
	retractall(base(_,_)),
	L = [[mom, 3], [dad, 2], [grandma, 6], [grandpa, 4]],
	maplist(my_index, L).


get_term(N, X) :-
	init,
	base(N, X).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top