Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Opposite letter program.

Status
Not open for further replies.

CaptainSafety

Programmer
Dec 4, 2012
1
IE
Hello. I am new to prolog. I am trying switch letters in a string to the opposite letter in the alphabet. This is my program, I can swap one letter but not change an entire String. Help me please.

letter(a, z).
letter(b, y).
letter(c, x).
letter(d, w).
letter(e, v).
letter(f, u).
letter(g, t).
letter(h, s).
letter(i, r).
letter(j, q).
letter(k, p).
letter(l, o).
letter(m, n).
letter(n, m).
letter(o, l).
letter(p, k).
letter(q, j).
letter(r, i).
letter(s, h).
letter(t, g).
letter(u, f).
letter(v, e).
letter(w, d).
letter(x, c).
letter(y, b).
letter(z, a).

swap(X) :- letter(Y, X), write(Y).
 
You can use ASCII codes so letter will be written :
Code:
letter(X, Y) :-
	char_code(X, C),
	C1 is  219 - C,
	char_code(Y, C1).
Be aware that it works only for lower cases letters.
Now for a string it's quite different because string are list of codes
Code:
string(X, Y) :-
	Y is 219 - X.

change_letters_in_string(S1, S2) :-
	maplist(string, S1, ST),
	string_to_list(S2, ST).
And you get
console prolog said:
?- change_letters_in_string("azbt", S2).
S2 = "zayg".
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top