SWI-Prolog 中的可逆谓词和字符串 [英] Reversible predicates and Strings in SWI-Prolog
问题描述
append/3
是一个非常强大的谓词.假设我想要一个以相同方式工作的谓词,但适用于 SWI-Prolog 的字符串.
append/3
is a very powerful predicate. Suppose I want a predicate that works the same way but for SWI-Prolog's strings.
我看到的最简单的方法是使用 string_codes/2
将这些字符串转换为列表,然后应用 append/3
,然后使用 string_codes/2代码>返回.这种方法的一个大问题是,如果两个变量不统一,
string_codes/2
就不起作用.
The easiest approach I see is to transform those strings into lists with string_codes/2
, then apply append/3
, then use string_codes/2
back. The big problem with this approach is that string_codes/2
does not work if both variables are not unified.
这是我想出的一个非常丑陋的解决方案,它检查哪些字符串在需要时统一应用string_codes/2
:
Here is an extremely ugly solution I came up with, which checks which strings are unified to apply string_codes/2
when needed:
append_strings(S1, S2, S3) :-
nonvar(S1),
nonvar(S2),!,
string_codes(S1, A),
string_codes(S2, B),
append(A,B,C),
string_codes(S3, C).
append_strings(S1, S2, S3) :-
nonvar(S1),
nonvar(S3),!,
string_codes(S1, A),
string_codes(S3, C),
append(A,B,C),
string_codes(S2, B).
append_strings(S1, S2, S3) :-
nonvar(S2),
nonvar(S3),!,
string_codes(S2, B),
string_codes(S3, C),
append(A,B,C),
string_codes(S1, A).
append_strings(S1, S2, S3) :-
nonvar(S3),
string_codes(S3, C),
append(A,B,C),
string_codes(S1, A),
string_codes(S2, B).
这会在以下情况下产生正确的结果:
This yields the correct results for the following cases:
?- append_strings("test","auie","testauie").
true.
?- append_strings("test",A,"testauie").
A = "auie".
?- append_strings(A,"auie","testauie").
A = "test" ;
false.
?- append_strings(A,B,"testauie").
A = "",
B = "testauie" ;
A = "t",
B = "estauie" ;
A = "te",
B = "stauie" ;
A = "tes",
B = "tauie" ;
A = "test",
B = "auie" ;
A = "testa",
B = "uie" ;
A = "testau",
B = "ie" ;
A = "testaui",
B = "e" ;
A = "testauie",
B = "" ;
false.
真的没有比这更简单的方法了吗?假设我想制作一大堆谓词来处理字符串,就像处理列表一样:我显然不想为所有这些都编写我为 append/3
所做的事情.但我也不想使用代码字符串,因为那样我就无法知道我是在操作普通列表还是真正的字符串.
Is there really no way to make things simpler than this? Suppose I want to make a whole bunch of predicates that work with strings just like they would with lists: I obviously don't want to have to write what I did for append/3
for all of them. But I also don't want to work with code strings because then I have no way of knowing whether I am manipulating a normal list or really a string.
推荐答案
只需使用 string_concat/3.和ISO atom_concat/3一样,可以在多种模式下使用,包括(-,-,+).
Just use string_concat/3. Like ISO atom_concat/3, it can be used in many modes, including (-,-,+).
这篇关于SWI-Prolog 中的可逆谓词和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!