Subject: RE: I am having trouble writing replace/4

From: "Rinke Hoekstra" <[email-masked]>
Date: Fri, 7 Jan 2000 12:42:15 +0100

It could be done a lot quicker:

replace_list([],[],List,List).
replace_list([HReplacant|TReplacant],[HReplacer|TReplacer],List,NewList):-
	replace(HReplacant,HReplacer,List,IList),
	replace_list(TReplacant,TReplacer,IList,NewList).

replace(_,_,[],[]).
replace(HReplacant,HReplacer,[HReplacant|Tail],[HReplacer|NewTail]):-
	replace(HReplacant,HReplacer,Tail,NewTail).
replace(HReplacant,HReplacer,[Head|Tail],[Head|NewTail]):-
	replace(HReplacant,HReplacer,Tail,NewTail).

This algorithm takes less steps (trace it to find out).

Regards,

	Rinke Hoekstra
	Amsterdam

-----Original Message-----
From: Pascal Vaillant [mailto:[email-masked]]
Sent: vrijdag 7 januari 2000 10:13
To: Douglas Miles
Cc: [email-masked]
Subject: Re: I am having trouble writing replace/4

> replaceList([],[],NothingToDo,NothingToDo):-!.
> replaceList([HeadBefore|TailBefore],[HeadAfter|TailAfter],Start,End):-!,
>         replace(HeadBefore,HeadAfter,Start,Midde),
>         replaceList(TailBefore,TailAfter,Middle,End).
>
> replace(_, _, [], []):-!.
> replace(A, B, [A|L], [B|R]) :- !,    replace(A, B, L, R).
> replace(A, B, [C|L], [C|R]) :-   replace(A, B, L, R).
>
> here is my trouble..
>
> ?- replaceList([a,b],[A,B],[1,2,3,a,b,c,x,y,z],O).
> A = b
> B = _G422
> O = [1, 2, 3, _G422, _G422, c, x, y, z]
> yes
>
> I guess the real question is how can I write a replace only once..  or
> rewrite replaceList?
>
> I want it to do this...
>
> ?- replaceList([a,b],[A,B],[1,2,3,a,b,c,x,y,z],O).
> A = _G421
> B = _G422
> O = [1, 2, 3, _G421, _G422, c, x, y, z]
> yes
>
> is copy_term/2 the key? I have tried a few tricks..
> or maybe numbervars can help?
>

No, it's simply because your test (second clause of replace/4) involves
unification, and not only equivalence. Hence, after having replaced a
by A, your current list becomes [b, etc.], and you try, at that point, to
unify A with b (which it has no reason to refuse :-)

This works :

replaceList([],[],NothingToDo,NothingToDo).

replaceList([HeadBefore|TailBefore],[HeadAfter|TailAfter],Start,End) :-
  replace(HeadBefore,HeadAfter,Start,Middle),
  replaceList(TailBefore,TailAfter,Middle,End).

replace(_,_,[],[]).

replace(A,B,[C|L],[D|R]) :-
  ((A==C) *->
   D=B ;
   D=C),
  replace(A,B,L,R).

Tschuess,

Pascal Vaillant
Berlin

----------------
* To UNSUBSCRIBE, please use the HTML form at

    http://www.swi.psy.uva.nl/projects/SWI-Prolog/index.html#mailinglist

or send mail to [email-masked] using the Subject:
"unsubscribe"
(without the quotes) and *no* message body.

** An ARCHIVE of this list is maintained at

    http://www.swi.psy.uva.nl/projects/SWI-Prolog/mailinglist/archive/