Jackieduckie
Jackieduckie

Reputation: 35

replacing elements in atoms in Prolog

I'm writing a prolog predicate which replace an element with another in a given atom. The predicate I wrote is like this:

replace_var(Expr0, Var, Val, Expr) :-
    Expr0 =.. Chars,
    chars_replaced(Chars, Rs),
    Expr =.. Rs.

chars_replaced(Chars, Rs) :-
    maplist(rep, Chars, Rs).

rep(Var,Val).
rep(C, C) :- dif(C,var).

The result I want it to return is something like:

-?replace_var(hello, l, w, X).
X = hewwo.

The problem is about the rep() predicate. I don't know how to write it or how to pass the Val and Var to the predicate.

Please give me some suggestions. Thanks!

Upvotes: 1

Views: 391

Answers (1)

CapelliC
CapelliC

Reputation: 60024

this is wrong

Expr0 =.. Chars

you need instead

atom_chars(Expr0, Chars)

and this one really puzzle me

rep(Var,Val).
rep(C, C) :- dif(C,var).

what do you mean, specially the second one ?

anyway, the whole could be

replace_var(Expr0, Var, Val, Expr) :-
  atom_chars(Expr0, Cs),
  maplist(rep(Var, Val), Cs, Ts),
  atom_chars(Expr, Ts).

 rep(C, T, C, T).
 rep(_, _, C, C).

disclaimer: untested code

Upvotes: 0

Related Questions