我第一次尝试将我的大脑包裹在 Prolog 周围(SWI-Prolog),并且我正在努力解决我确定的基础知识。我正在尝试使用诸如“pie”之类的字符串并打印出它的军事北约拼写,看起来像这样:
spellWord("Pie").
Papa
India
Echo
目前我只是想验证我是否正确使用了 [H|T] 语法和 Write 函数。我的功能是:
spellWord(String) :- String = [H|T], writeChar(H), spellWord(T).
writeChar(String) :- H == "P", print4("Papa").
调用
spellWord("Pie")
时.这目前只返回false。
最佳答案
SWI-Prolog 有几种不同的表示你可能称之为“字符串”的东西。
您应该阅读文档,但目前,您至少有两个选择。
选择 1 : 使用标志来制作双引号字符串代码列表
$ swipl --traditional
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 7.3.19-57-g9d8aa27)
Copyright (c) 1990-2015 University of Amsterdam, VU Amsterdam
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.
For help, use ?- help(Topic). or ?- apropos(Word).
?- X = "abc".
X = [97, 98, 99].
此时,您的方法应该有效,因为您现在有一个列表。
选择2 :使用带有反引号的新代码列表语法
?- X = `abc`.
X = [97, 98, 99].
当然,还有谓词可以在原子、代码列表、字符列表和字符串之间进行转换。所以,要制作一个字符列表(单字符原子),你有:
atom_chars/2
char_code/2
string_chars/2
至于您的谓词定义,请考虑在头部使用统一。此外,不要将副作用(打印)与谓词的作用混为一谈。让顶层(Prolog 解释器)为您打印。
nato(p, 'Papa').
nato(i, 'India').
nato(e, 'Echo').
% and so on
word_nato([], []).
word_nato([C|Cs], [N|Ns]) :-
char_code(Char, C),
char_type(U, to_lower(Char)),
nato(U, N),
word_nato(Cs, Ns).
有了这个:
?- word_nato(`Pie`, Nato).
Nato = ['Papa', 'India', 'Echo'].
我使用字符(单字母原子)而不是字符代码,因为它们更容易编写。
最后,您可以使用以下标志和
set_prolog_flag/2
在运行时更改 Prolog 如何处理用双引号括起来的字符串。例如:
$ swipl
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 7.3.19-40-g2bcbced)
Copyright (c) 1990-2015 University of Amsterdam, VU Amsterdam
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.
For help, use ?- help(Topic). or ?- apropos(Word).
?- current_prolog_flag(double_quotes, DQs).
DQs = string.
?- string("foo").
true.
?- set_prolog_flag(double_quotes, codes).
true.
?- X = "foo".
X = [102, 111, 111].
?- set_prolog_flag(double_quotes, chars).
true.
?- X = "foo".
X = [f, o, o].
?- set_prolog_flag(double_quotes, atom).
true.
?- X = "foo".
X = foo.
关于string - Prolog获取字符串的头部和尾部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36604729/