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?
4 Answers
2
votes
I would use code_type/2 to ensure that any entered name starts with a capital letter.
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.
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.
Here is the code:
:- 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)).
Example of use:
$ 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'.
Hope this helps!
1
votes
1
votes
to_upper/2orto_lower/2for converting a character to/from upper and lower case. There are also predicates such asread_line_to_codes/2which will read a "raw" input line rather than attempting to interpret it as a Prolog term (which is whatread/1does). You might also want to look atatom_codes/2. Have a look at those, give something a try, and see if you have more specific questions afterwards. - lurkercode_type/2which has thelower/1,to_lower/1,upper/1, andto_upper/1options of the second argument.char_type/2works the same way, but on single-character atoms. SWI has quite some support for case-conversion :-) - Wouter Beek