Newsgroups: comp.lang.prolog
Path: cantaloupe.srv.cs.cmu.edu!das-news2.harvard.edu!oitnews.harvard.edu!purdue!lerc.nasa.gov!magnus.acs.ohio-state.edu!math.ohio-state.edu!cs.utexas.edu!news.sprintlink.net!newsfeed.internetmci.com!news.mel.aone.net.au!inferno.mpx.com.au!news.unimelb.EDU.AU!cs.mu.OZ.AU!munta.cs.mu.OZ.AU!fjh
From: fjh@munta.cs.mu.OZ.AU (Fergus Henderson)
Subject: Re: Q: Write my own occurs check?
Message-ID: <9525602.14322@mulga.cs.mu.OZ.AU>
Sender: news@cs.mu.OZ.AU (CS-Usenet)
Organization: Computer Science, University of Melbourne, Australia
References: <fry.808374087@Csli.Stanford.EDU> <fry.808481070@Csli.Stanford.EDU> 	<9522913.25982@mulga.cs.mu.OZ.AU> <geoff.810164749@coral.cs.jcu.edu.au> <THOMASL.95Sep4122503@groucho.csd.uu.se>
Date: Tue, 12 Sep 1995 16:09:00 GMT
Lines: 62

thomasl@groucho.csd.uu.se (Thomas Lindgren) writes:

[...]
>	; functor(X,P,N),
>	  functor(Y,P,N),
>	  X =.. [_|Xs],
>	  Y =.. [_|Ys],
>	  unify_list(Xs,Ys)
>	).
>
>unify_list([],[]).
>unify_list([X|Xs],[Y|Ys]) :-
>	unify(X,Y),
>	unify_list(Xs,Ys).

I can suggest one possible improvement: it will most likely be more
efficient if you use `arg' rather than `=..' to get the arguments.
`=..' is usually a bit slower, since it needs to allocate a bunch
of cons cells on the heap.

	...
	; functor(X,P,N),
	  functor(Y,P,N),
	  unify_args(0,N,X,Y)
	).

unify_args(N0, N, X, Y) :-
	( N0 = N ->
		true
	;
		N1 is N0 + 1,
		arg(N1, X, X_Arg),
		arg(N1, Y, Y_Arg),
		unify(X_Arg, Y_Arg),
		unify_args(N1, N, X, Y)
	).

If you really want to optimize the last cycle out of it,
you might prefer traversing the arguments right-to-left:

	...
	; functor(X,P,N),
	  functor(Y,P,N),
	  unify_args(N,X,Y)
	).

unify_args(N, X, Y) :-
	( N0 = 0 ->
		true
	;
		arg(N, X, X_Arg),
		arg(N, Y, Y_Arg),
		unify(X_Arg, Y_Arg),
		N1 is N0 - 1,
		unify_args(N1, X, Y)
	).

-- 
Fergus Henderson             |  #define x t=a[i],a[i]=a[m],a[m]=t
                             |  char a[]=" 12345678";main(m,i,j,t){for(i=m;i<
fjh@cs.mu.oz.au              |  9;x,i++)for(x,j=m;--j?(t=a[m-j]-a[m])-j&&t+j:
http://www.cs.mu.oz.au/~fjh  |  main(m+1)*0;);m-9||puts(a+1);} /* 8 queens */
