%	call 'family!' to start accepting set form of English query.
%	Uses unification on principal functors (non-standard).

lib family_db!		% loads family database from library

family :-
	repeat,
	read_and_answer_question,
	!.

read_and_answer_question :-
	read_sentence(X),
	answer_question(X), !,
	X = [].

read_sentence([]) :- #'.', !.
read_sentence([]) :- #'?', !.
read_sentence([X|Y]) :- #X, read_sentence(Y).

answer_question([]) :- !.
answer_question([who, is, the, Attribute, of, Object]) :- !,
	setof(X, Attribute(Object, X), L),
	print_list(L).
answer_question([the, Attribute, of, Object, is, Value]) :-
	assert(Attribute(Object, Value)),
	!.
answer_question([do, you, know, what, a, Attribute, is]) :-
	confirm(Attribute, Answer),
	print(Answer),
	!.
answer_question([what, is, a, X]) :-
	(confirm(X, yes) -> pp X | print("I don't know")),
	!.
answer_question(Garbage) :-
	print("I don't understand.").

confirm(Attribute, yes) :- Attribute(X, Y), !.
confirm(_, no).

print_list([])	:- !, print("I don't know.").
print_list([A]) :- !, print(A).
print_list([A|B]) :- prin(A, ', '), print_list(B).

setof(X, P, L1) :-
	bagof(X, P, L),
	sort(L, L1).

sort([A|B], Y) :- !, sort(B, X), insert(A, X, Y).
sort([], []).

insert(X, [], [X]) :- !.
insert(X, [X|Y], [X|Y]) :- !.
insert(X, [A|B], [A|B1]) :- X > A, !, insert(X, B, B1).
insert(X, L, [X|L]).
