substituting an ietm in list of lists
Author Message
substituting an ietm in list of lists

Hi,

I have been fiddling about with a small piece of code that when given a
number, an item, a list of lists will return a list of lists with the item
substituted as the number.
ie/ the list will look like this [ [1,2,3,4,5],
[1,2,3,4,5],
[1,2,3,4,5],
[1,2,3,4,5] ]

when replace(1, A, List, Newlist). is called the output should look like
[ [A,2,3,4,5],
[1,2,3,4,5],
[1,2,3,4,5],
[1,2,3,4,5] ]
if called again then the second 1 should be replaced with an A.

This piece of code works fine when taking one list.  However when I modify it
to deal with a list of lists (by including another case) it fails to work.

;;; Base case:      the square to be replaced is the head of the list.
replace(Number, Item, [ Number | Tail ], [ Item | Tail ]).

;;; Recursive case:     keep going down the list until the base case applies.
replace(Number, Item, [ Head | Tail ], [ Head | Newtail ]) :-
replace(Move, Item, Tail, Newtail).

Marc...

Tue, 26 May 1998 03:00:00 GMT
substituting an ietm in list of lists

Quote:

>Hi,

>    I have been fiddling about with a small piece of code that when given a
>number, an item, a list of lists will return a list of lists with the item
>substituted as the number.

Hi Marc,
greetings to the Sussex University.

The following piece of code is what I used in a theorem prover I built recently.
I seem to remember I did not write it, but took it from somewhere...
cannot remember where....
It is powerful enough to handle your case and it does not need any explanation.
Bye,
Alessio

% substitute(Sottot , in expression TERM , with the term Sottot1 , Result).

substitute(Term,Term,Term1,Term1):- !.
substitute(_,Term,_,Term):-
atomic(Term),!.
substitute(Sottot,Term,Sottot1,Term1):-
Term=.. [F|Argomm],
substitute_list(Sottot,Argomm,Sottot1,Argomm1),
Term1=..[F|Argomm1].
substitute_list(_,[],_,[]).
substitute_list(Sottot,[Term|Terms],Sottot1,[Term1|Terms1]):-
substitute(Sottot,Term,Sottot1,Term1),
substitute_list(Sottot,Terms,Sottot1,Terms1).

--

Via Rigola 5           |      Phone: +39 2 2428370/6883486
20159 Milano, ITALY    |      Politecnico di Milano, Italy

Wed, 27 May 1998 03:00:00 GMT

 Page 1 of 1 [ 2 post ]

Relevant Pages