0
votes

I'm having trouble writing a predicate in the Prolog:

In Prolog, define a predicate replace1(L1, L2) that is satisfied when the list L2 is derived from the list L1 by replacing each element with an element of the form element * element.

Example: L1 = [1, aa, 3], L2 = [1 * 1, aa * aa, 3 * 3].

I tried this way, but this predicate only works for numbers:

replace1 ([], []) :- !.
replace1 ([X | Xs], [Z | Zs]) :-
  Z is X * X,
  replace1 (Xs, Zs).
1

1 Answers

0
votes

You are using is/2 which is arithmetic evaluation operator. You could just use = and would get what you want.

replace([], []).
replace([X|Xs], [Y|Ys]) :-
    Y = X * X,
    replace(Xs, Ys).

This gives:

| ?- replace([1, aa, 3], X).
X = [1*1,aa*aa,3*3]

You can also just use pattern matching within the head itself:

replace([], []).
replace([X|Xs], [X*X|Ys]) :-  replace(Xs, Ys).