abc
abc

Reputation: 153

Predicate that will swap the first two letters in an atom in Prolog

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

Answers (1)

Paulo Moura
Paulo Moura

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

Related Questions