Prolog中字符串的串联 [英] Concatenation of Strings in Prolog

查看:198
本文介绍了Prolog中字符串的串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Prolog中连接4个字符串。我可以连接2个和3个字符串,但无法使其与4个字符串一起使用。到目前为止,这就是我的意思:

I am trying to concatenate 4 strings in Prolog. I am able to concatenate 2 and 3 strings but I can't get it to work with 4. This is what I have so far:

join2(String1,String2,Newstring) :-
   name(String1,L1), name(String2,L2),
   append(L1,L2,Newlist),
   name(Newstring,Newlist).

join3(String1,String2,String3,Newstring) :-
   join2(String1,String2,S),
   join2(S,String3,Newstring).

join4(String1,String2,String3,String4,Newstring) :-
   join3(String1,String2,String3,Newstring),
     join2(String1,String2,S),
     join2(S,String3,Newstring).
   join3(Newstring,String4,Newstring).


推荐答案

我不确定您的约束是什么,但是您还可以使用SWI的 append / 2 maplist / 3

I'm not sure what your constraints are, but you can also use SWI's append/2 and maplist/3:

concatenate(StringList, StringResult) :-
    maplist(atom_chars, StringList, Lists),
    append(Lists, List),
    atom_chars(StringResult, List).

然后,您可以连接任意数量的:

Then you can concatenate as many as you like:

?- concatenate(["hello", ", ", "world"], String).
String = 'hello, world'.

?- concatenate(["hey, ", "you ", "don't ", "say!"], String).
String = 'hey, you don\'t say!'.

?-

请注意,以上假定您使用的是 SWI Prolog中的> 默认设置:

Note that the above assumes you are using the default setting in SWI Prolog:

:- set_prolog_flag(double_quotes,atom).

其中 abc 表示Prolog原子相当于'abc'

where "abc" represents a Prolog atom and is equivalent to 'abc'.

这篇关于Prolog中字符串的串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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