Reputation: 153
I have to write a predicate which will swap the first two letters in an atom of length two or more. Length one atoms are unchanged.
?- interchange(cat,X).
X = act;
I am suppose to use name function to split the atom:
?- name(food,[X,Y|Z]).
Z = "od",
Y = 111,
X = 102 ;
This is the code that I wrote:
inter(X,[]).
inter(X,[Q|W]):-
name(X,[H,T|R]), reverse([H,T],W), !, append([W],[R],F).
I get this output:
P = [] ;
P = [_VCSF, 111, 102] ;
How can I improve my code to get desired output. Thanks in Advance.
Upvotes: 1
Views: 520
Reputation: 18663
Using the standard atom_chars/2
built-in predicate:
swap_first_two_characters(Atom, SwappedAtom) :-
( atom_chars(Atom, [Char1, Char2| Chars]) ->
% two or more chars
atom_chars(SwappedAtom, [Char2, Char1| Chars])
; % one char atom
SwappedAtom = Atom
).
Upvotes: 1