Prolog,使用大写字母 [英] Prolog, working with capital letter
问题描述
我正在 SWI-Prolog 中进行数据库项目.问题是我想使用我从输入中读取的运动员的名字.我需要用大写字母保存他们的名字,但 prolog 将这些解释为变量.任何想法如何解决这个问题?
I am working on database project in SWI-Prolog. Problem is that i want to work with names of Sportsmen which i read from input. I need to save their names with capital letters, but prolog interprets these as variables. Any ideas how to fix this?
推荐答案
我会使用 code_type/2
来确保任何输入的名称都以大写字母开头.
I would use code_type/2
to ensure that any entered name starts with a capital letter.
由于您希望用户输入带有小写或大写字母的名称,因此我对使用 read_line_to_codes/2
读取的代码列表进行了大小写转换.
Since you want to allow a user to enter a name with a letter that is either lower- or uppercase, I do the case conversion on the codes list that I read with read_line_to_codes/2
.
由于您想将名称存储在数据库中,因此我使用 dynamic/1
声明我将添加一些 sportsname/1
条目,并且我使用 assert/1
将特定名称添加到数据库中.
Since you want to store the names in a database, I use dynamic/1
to declare that I will be adding some sportsname/1
entries, and I use assert/1
to add a specific name to the database.
代码如下:
:- dynamic(sportsname/1).
:- initialization(input).
input:-
repeat,
format(user_output, 'Please enter a name (or type `quit`):\n', []),
read_line_to_codes(user_input, Codes1),
(
atom_codes(quit, Codes1)
->
!, true
;
capitalize(Codes1, Codes2)
->
atom_codes(Name, Codes2),
assert(sportsname(Name)),
format(current_output, 'Sportsname ~a writen to database.\n', [Name]),
fail
;
fail
).
capitalize([], []).
capitalize([H1|T], [H2|T]):-
code_type(H2, to_upper(H1)).
使用示例:
$ swipl sport_names.pl
Please enter a name (or type `quit`):
|: john
Sportsname John writen to database.
Please enter a name (or type `quit`):
|: James
Sportsname James writen to database.
Please enter a name (or type `quit`):
|: suzan
Sportsname Suzan writen to database.
Please enter a name (or type `quit`):
|: quit
?- sportsname(X).
X = 'John' ;
X = 'James' ;
X = 'Suzan'.
希望这会有所帮助!
这篇关于Prolog,使用大写字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!