Reputation: 1056
I'm trying to convert a char array to a string, and then convert this string a list. This is what I want:
code_list=[97 97]
string_s="aa"
string_list=[aa]
I'm not sure about notation, whether I used them correctly or not.
Upvotes: 4
Views: 8033
Reputation: 10102
Commonly, Prolog systems do not support a separate string data type. Instead, there are atoms, lists of codes, and lists of characters which serve the very purpose of strings. So if you are learning Prolog, stick to those types. The following query works in any Prolog system:
?- Code_list = [97, 97], atom_codes(Atom, Code_list), atom_chars(Atom, Chars).
Code_list = [97,97], Atom = aa, Chars = [a,a].
This should answer your question.
For completeness, remark that strings as a separate data type are very rare. And most often they are not a valid extension to the ISO Prolog standard. SWI7 has particularly odd behavior with respect to strings. The first thing to try is the following query:
?- phrase("abc","abc").
This query should succeed, otherwise learning DCGs (one of Prolog's main features) will be very cumbersome to you. In SWI7 the default is:
?- phrase("abc","abc").
ERROR: Type error: `list' expected, found `"abc"' (a string)
So the double quote notation means two different things. To get consistent behavior, you have several options.
Install SWI Prolog 6, or another system like GNU or SICStus Prolog.
Call SWI with swipl --traditional
which fixes many of the incompatibilities.
Change the Prolog flag double_quotes
to codes
or chars
. See this answer how this is done.
Upvotes: 2
Reputation:
A few examples that may help you understand the different ways to represent "strings" in SWI-Prolog, and convert from one representation to another (note that Prolog doesn't really have types, so this is not a type converstion).
This is all for SWI-7 and later:
$ swipl --version
SWI-Prolog version 7.1.27 for x86_64-linux
Now, from the top level:
?- atom(foo).
true.
?- string("foo").
true.
?- is_list(`foo`).
true.
?- is_list([f,o,o]).
true.
?- atom_chars(A, [f,o,o]).
A = foo.
?- atom_codes(foo, Codes).
Codes = [102, 111, 111].
?- string_codes(Str, `foo`).
Str = "foo".
?- write(`foo`).
[102,111,111]
true.
?- string_chars(Str, [f,o,o]).
Str = "foo".
You should read the documentation on the used predicates if you want to learn a bit more.
Upvotes: 5
Reputation: 49803
The proper way to express your example would be:
Code_list = [97, 97]
String_s = "aa"
(I'm not quite sure what you mean by the last line.)
Upvotes: 1