Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 40 ยท Data Structures and Parsing

Atoms, Strings and Characters

Work with text in Prolog. Learn the difference between atoms, strings and code lists, convert between them, and use atom_concat, sub_atom, split_string, atom_number and format/2.

Text in Prolog comes in several forms, and knowing which one you hold is half the battle. You will meet atoms (hello, 'Hello World'), strings ("hello"), lists of character codes ([104,101,108,108,111]) and lists of characters ([h,e,l,l,o]). SWI-Prolog 7 and later treat double-quoted text as a real string type; older systems and strict ISO Prolog read "..." as a list of codes. This lesson uses SWI-Prolog conventions and shows how to convert between all the forms and process text.

The four text types

Written as Type Typical use
hello, 'Hello, World' atom names, keys, symbols in rules
"hello" string text you read, build or print
[0'h, 0'i] or [104, 105] list of codes low-level character processing
[h, i] list of chars pattern matching on characters

Atoms are stored once in a table and compared by identity, which makes them fast as keys. Strings are ordinary text values and can be built and discarded freely. Quote an atom with single quotes when it starts with a capital letter, contains spaces or special characters: 'Ann Lee'.

The type-check predicates are atom/1, string/1, number/1, atomic/1 and is_list/1. The "generic" built-ins atom_length/2, sub_string/5, string_concat/3 and the text_* family accept either atoms or strings as input.

Converting between forms

PROLOG
?- atom_chars(hello, Cs).
Cs = [h, e, l, l, o].

?- atom_codes(abc, Codes).
Codes = [97, 98, 99].

?- atom_string(hello, S).
S = "hello".

?- term_to_atom(foo(bar), A).
A = 'foo(bar)'.

?- atom_number('3.5', N).
N = 3.5.

?- atom_number(abc, N).
false.

?- upcase_atom('hello world', U).
U = 'HELLO WORLD'.

?- char_code(a, C).
C = 97.

atom_number/2 is the friendly way to turn text into a number: it fails (rather than raising an error) when the text is not a number. atom_to_term/3 and term_to_atom/2 convert between text and arbitrary terms, useful for reading user input as Prolog syntax.

Building and taking apart atoms

atom_length/2 gives the size. atom_concat/3 joins two atoms and, run backwards, splits an atom in every possible way:

PROLOG
?- atom_length(hello, N).
N = 5.

?- atom_concat(abc, def, X).
X = abcdef.

?- atom_concat(X, Y, ab).
X = '',  Y = ab ;
X = a,   Y = b ;
X = ab,  Y = ''.

sub_atom(Atom, Before, Length, After, Sub) is the general substring predicate, working in all directions. Fill in what you know; Prolog finds the rest.

PROLOG
?- sub_atom(hello, 1, 3, After, Sub).
After = 1,
Sub = ell.

?- sub_atom(hello_world, Before, _, 0, world).
Before = 6.

?- sub_atom(hello_world, 0, 5, _, Start).
Start = hello.

The second query asks "where does world occur such that nothing follows it?" and the answer is its starting position. With unbound Before and Length it enumerates every substring on backtracking, so it can also check sub_atom(Text, _, _, _, Word) for containment (add a cut or once/1 when you only need yes or no). The string versions have the same shape: sub_string/5, string_concat/3, string_length/2.

Splitting and joining

Splitting text on separators is the most common text task. split_string(String, SepChars, PadChars, SubStrings) does it in one call:

PROLOG
?- split_string("a,b,,c", ",", "", Parts).
Parts = ["a", "b", "", "c"].

?- split_string("  hi  ", "", " ", Parts).
Parts = ["hi"].

?- split_string("/home//jan///nice/path", "/", "", L).
L = ["", "home", "", "jan", "", "", "nice", "path"].

SepChars are the characters that separate fields (each one counts as a separator); PadChars are characters stripped from the ends of each field. Passing an empty separator list with padding is the standard way to trim a string. To join strings again use atomic_list_concat/3, which also splits when given a separator and an unbound list:

PROLOG
?- atomic_list_concat([a, b, c], '-', R).
R = 'a-b-c'.

?- atomic_list_concat(Parts, ',', 'x,y,z').
Parts = [x, y, z].

The stand-in below models the tricky parts, the backwards atom_concat and split_string padding and separator rules, in Python.

Python atom_concat and split_string (Python model)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output with format/2

format(Template, Args) prints text with directives that start with ~:

Directive Meaning
~w write any term
~a write an atom
~d write an integer (~D adds thousands separators)
~2f float with 2 decimals
~s write a list of character codes as text
~q write with quotes where needed
~p print via print/1
~n newline
~t and `~ `
PROLOG
?- format("~w has ~d items~n", [cart, 3]).
cart has 3 items

?- format("pi is about ~2f~n", [3.14159]).
pi is about 3.14

?- format(atom(A), "~w-~w", [a, b]).
A = 'a-b'.

The last form, format(atom(A), ...), builds an atom (or string(S) builds a string) instead of printing, which is the idiomatic way to assemble text. A single argument that is not a list can be passed directly: format("~w~n", hello).

A worked example: palindromes

Putting several converters together gives a short program:

PROLOG
palindrome(Word) :-
    atom_chars(Word, Chars),
    reverse(Chars, Chars).
PROLOG
?- palindrome(level).
true.

?- palindrome(prolog).
false.

Both occurrences of Chars mean the reversed list must be identical to the original: unification does the comparison. To ignore case and spaces, first normalize with downcase_atom/2 and filter characters with exclude/3. Another use is reading unknown text safely: catch(atom_number(Text, N), _, fail).

Python Normalize, reverse, compare (Python model of the Prolog steps)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Using = between an atom and a string: hello = "hello" is false because they are different types. Convert with atom_string/2, or compare with text_concat/3 or == after converting.
  • Forgetting single quotes around atoms that start with a capital letter or contain spaces: Ann is a variable.
  • Expecting atom_length/2 to count bytes. It counts characters.
  • Using atom_concat/3 on a number and expecting an atom back to be a number again: atom_concat(1, 2, X) gives the atom '12'; use atom_number/2 to convert.
  • Creating huge numbers of atoms in a long-running loop. Atoms are garbage-collected in SWI-Prolog, but strings are the better type for transient text.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does atom_concat(X, Y, ab) give on backtracking?

    Run backwards, atom_concat enumerates every way to split the atom, including the empty ends.
  2. 2. How do you turn the text '42' into the number 42 without an error on bad input?

    atom_number fails on text that is not a number, which makes it easy to use as a test.
  3. 3. What is split_string(" hi ", "", " ", P)?

    With no separators there is one field; the pad characters (spaces) are removed from both ends.
  4. 4. Which call builds an atom from a formatted template instead of printing it?

    Giving atom(A) or string(S) as the first argument of format/3 captures the output.

Summary

  • Prolog text comes as atoms, strings, code lists and char lists; SWI-Prolog reads "..." as a string.
  • Convert with atom_chars, atom_codes, atom_string, atom_number, char_code; case-change with upcase_atom and downcase_atom.
  • atom_concat/3 and sub_atom/5 work in all directions; split_string/4 and atomic_list_concat/3 split and join.
  • format/2 and format/3 print or build text with ~w, ~a, ~d, ~2f, ~n.
  • Atoms and strings are different types: abc = "abc" is false.

Next: DCG Grammars and Parsing