Search code examples
prologtype-conversionswi-prolog

Convert a char list to a string in Prolog


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.


Solution

  • 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.