将交换 Prolog 中原子中前两个字母的谓词 [英] Predicate that will swap the first two letters in an atom in Prolog

查看:42
本文介绍了将交换 Prolog 中原子中前两个字母的谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写一个谓词来交换长度为 2 或更多的原子中的前两个字母.长度为一的原子不变.

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;

我想使用 name 函数来拆分原子:

I am suppose to use name function to split the atom:

?- name(food,[X,Y|Z]).

Z = "od",
Y = 111,
X = 102 ;

这是我写的代码:

inter(X,[]).

inter(X,[Q|W]):-
    name(X,[H,T|R]), reverse([H,T],W), !, append([W],[R],F).

我得到这个输出:

P = [] ;

P = [_VCSF, 111, 102] ;

如何改进我的代码以获得所需的输出.提前致谢.

How can I improve my code to get desired output. Thanks in Advance.

推荐答案

使用标准的 atom_chars/2 内置谓词:

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
    ).

这篇关于将交换 Prolog 中原子中前两个字母的谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆