append/3
是一個非常強大的謂詞。假設我想要一個和SWI-Prolog的字符串一樣的謂詞。SWI-Prolog中的可逆謂詞和字符串
我看到的最簡單的方法是將這些字符串轉換爲與列表,然後應用append/3
,然後使用回來。這種方法的一個大問題是如果兩個變量都不統一,不起作用。
這是一個極其醜陋的解決方案,我想出了,檢查哪些字符串是統一適用需要的時候:
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).
這將產生以下情況下,正確的結果:
?- 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
。但我也不想使用代碼字符串,因爲我無法知道我是在操縱一個普通列表還是一個字符串。
最簡單的方法是不直接使用字符串。相反[使用'chars'](http://stackoverflow.com/a/36645725/772868)。 – false
你的定義失敗了'append_strings(Xs,Ys,Zs)'。它應該產生一個實例化錯誤。 – false
@false但是,我不能區分列表和字符串。假設我想要一個謂詞轉置,它轉換一個列表,但對於一個根據換行符轉換的字符串。有了字符清單,我無法知道我是否在使用字符串。 – Fatalize