Newsgroups: comp.lang.prolog
Path: cantaloupe.srv.cs.cmu.edu!das-news2.harvard.edu!news2.near.net!howland.reston.ans.net!swrinde!pipex!uunet!in1.uu.net!munnari.oz.au!cs.mu.OZ.AU!mundil.cs.mu.OZ.AU!conway
From: conway@mundil.cs.mu.OZ.AU (Thomas Charles CONWAY)
Subject: Re: Help!! union without cut!?
Message-ID: <9509715.29585@mulga.cs.mu.OZ.AU>
Sender: news@cs.mu.OZ.AU (CS-Usenet)
Organization: Computer Science, University of Melbourne, Australia
References: <3ldruq$fka@cpccux0.cityu.edu.hk>
Date: Fri, 7 Apr 1995 05:30:00 GMT
Lines: 58

93848283@cpccspc.cityu.edu.hk (Louis Chan  8-)~~) writes:


>Help....
>
>Can I write a predicte of union/3 without using cut and give me only one
>answer!?
>
>e.g. union([1,2,3],[3,4,5],U). 
>     U=[1,2,3,4,5].
>     no.
>

Here is my suggested solution:

union(As, Bs, Cs) :-
	det_merge(As, Bs, Cs).

% when declaration for NU-Prolog
:- det_merge(As, Bs, _) when As and Bs.

det_merge(As, Bs, Cs) :-
	(
		As = []
	->
		Cs = Bs
	;
		Bs = []
	->
		Cs = As
	;
		As = [A|As1],
		Bs = [B|Bs1]
	->
		(
			A < B
		->
			Cs = [A,B|Ds]
		;
			Cs = [B,A|Ds]
		),
		det_merge(A1, Bs1, Ds)
	).

Of course, this is kind of cheating, since -> does a hard cut
across the condition, though in this case it isn't too bad.

Of course, if you read rok's post a week or so ago about the
subset predicate, how best you should write union depends on
the representation of the sets.

In the library I use, a set is an unsorted list containing 
duplicates, so union/3 is defined:

union(As, Bs, Cs) :-
	append(As, Bs, Cs).

Thomas
