Strings and Runes in Prolog

Our first example demonstrates how to work with strings and characters in Prolog. In Prolog, strings are typically represented as lists of character codes or atoms.

% Main predicate
main :-
    % Define a string (list of character codes) representing "hello" in Thai
    S = "สวัสดี",
    
    % Get the length of the string (in bytes)
    string_length(S, Len),
    format('Len: ~w~n', [Len]),
    
    % Print the hex values of each byte
    format('Hex values: '),
    string_codes(S, Codes),
    maplist(print_hex, Codes),
    nl,
    
    % Count the number of characters
    atom_chars(S, Chars),
    length(Chars, CharCount),
    format('Character count: ~w~n', [CharCount]),
    
    % Print each character with its position
    print_chars(Chars, 0),
    
    % Demonstrate character comparison
    examine_char('t'),
    examine_char('ส').

% Helper predicate to print hex values
print_hex(Code) :-
    format('~|~`0t~16r~2+ ', [Code]).

% Helper predicate to print characters with their positions
print_chars([], _).
print_chars([Char|Rest], Index) :-
    format('~w starts at ~w~n', [Char, Index]),
    NextIndex is Index + 1,
    print_chars(Rest, NextIndex).

% Helper predicate to examine a character
examine_char(Char) :-
    (Char = 't' ->
        writeln('found tee')
    ; Char = 'ส' ->
        writeln('found so sua')
    ; true
    ).

In this Prolog example, we’re working with a Thai string “สวัสดี”. Here’s a breakdown of what the code does:

  1. We define the string S as a list of character codes.

  2. We use string_length/2 to get the length of the string in bytes.

  3. To print the hex values of each byte, we convert the string to a list of character codes and use maplist/2 with a custom print_hex/1 predicate.

  4. To count the number of characters, we convert the string to an atom and then to a list of characters using atom_chars/2.

  5. We print each character with its position using a recursive print_chars/2 predicate.

  6. The examine_char/1 predicate demonstrates how to compare characters in Prolog.

To run this program, you would typically save it in a file (e.g., strings_and_chars.pl) and then consult it in a Prolog interpreter:

?- [strings_and_chars].
?- main.
Len: 18
Hex values: e0 b8 aa e0 b8 a7 e0 b8 b1 e0 b8 aa e0 b8 94 e0 b8 b5 
Character count: 6
ส starts at 0
ว starts at 1
ั starts at 2
ส starts at 3
ด starts at 4
ี starts at 5
found so sua
true.

Note that Prolog doesn’t have a built-in concept of “runes” like Go does. Instead, we work with characters directly. The handling of Unicode characters may vary depending on the Prolog implementation and the terminal’s capabilities.