/*
 * Copyright (c) 1995, 1996 Gunther Schadow.  All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * assoc/4, assoc/3, assoc/2, dissoc - association list handling
 *
 * An association list (alist) is a list that consists of elements
 * which are functors with arguments. The functor is interpreted as
 * a token and the arguments as a list of objects that are associated
 * with the token.
 * The predicate assoc/4 is the most general predicate, whereas the
 * others handle only special cases either more economically. It looks
 * for the Token in the Alist and reports its Value and the Alist with
 * the Token removed in AlistRest.
 * The predicate assoc/3 just looks for the Token in the Alist and
 * reports its Value, while assoc/2 looks for the Token with the given
 * arguments. Finally, dissoc/3 dissociates the Token from the Alist1
 * and reports the result in Alist2.
 */

:- module(alist,[assoc/4, assoc/3, assoc/2,
	assoca/4, assoca/3, assoca/2, dissoc/3]).

assoc(Alist, Token, Value, AlistRest) :-
	select(Alist, X, AlistRest),
	X =.. [Token|Value].

assoc(Alist, Token, Value) :-
	member(X, Alist),
	X =.. [Token|Value].

assoc(Alist, Functor) :-
	member(Functor, Alist).

assoca(Alist, Token, Value, AlistRest) :-
	select(Alist, X, AlistRest),
	X =.. [Token|Value].
assoca(Alist, _, [], Alist).

assoca(Alist, Token, Value) :-
	member(X, Alist),
	X =.. [Token|Value].
assoca(_, _, []).

setd(X,Y) :- nonvar(Y), X=Y.
setd(X,Y) :- nonvar(X), var(Y), X=Y.
setd(X,Y) :- var(X), var(Y), X=''.

assoca(Alist, Functor) :-
	member(Functor, Alist).
assoca(Alist, Functor) :-
	Functor =.. [F|A],
	Al^(member(G,Alist), G =.. [F|Al]),
	append(A,_,At),
	append(Al,_,Al1),
	maplist(setd, At, Al1),
	Functor =.. [F|A].
assoca(_, Functor) :-
	Functor =.. [F|A],
	findall(X,
	(
	    member(X,A),
    	    ( var(X) -> X = '' ; true )
	), B),
	Functor =.. [F|B].

dissoc(Alist1, Token, Alist2) :-
	select(Alist1, X, Alist2),
	X =.. [Token|_].
dissoc(Alist1, _, Alist1).

