15. Text as characters
In chapter 14, a sentence was a list of words. To read real text, such as Markdown, we need to go down one more level, to single characters.
Atoms and lists of characters
In C#Prolog, a piece of text is an atom in single quotes, such as 'Hello, world'. atom_chars/2 turns an atom into a list of characters, and back. Each character is an atom of length one.
A few more things about quoted atoms.
\nin a quoted atom is a new line.- To put a single quote in an atom, write it twice, as in
'it''s'. - A backslash at the end of a line continues the atom on the next line. The new line itself is not part of the atom.
You can also write text in double quotes, such as "hi". As the ISO standard says, C#Prolog reads it as a list of character codes by default. Codes are numbers, so they are hard to read. The directive :- set_prolog_flag(double_quotes, chars). makes the clauses and queries after it read double quotes as a list of characters instead.
A line that starts with :- is a directive. It runs a goal while the text is read. Other Prolog systems don't agree on what double quotes mean. For example, SWI-Prolog reads them as its own string type. So this tutorial uses quoted atoms and atom_chars/2, which work the same everywhere.
Numbers and characters
number_chars/2 turns a list of characters into a number, and back.
Note that '4' in quotes is the character, and 4 without quotes is the number.
Reading digits with a grammar
Grammar rules work on any list, so they work on a list of characters too. Here is a grammar for an integer.
digit//1reads one character, and checks in braces that it is between'0'and'9'.@>=and@=<compare two terms in the standard order, like@<in chapter 8. For characters, that is alphabetical order, and the digits come in the right order.digits//1reads one or more digits. The first clause tries to read as many as it can.integer//1turns the digits into a number in braces.
A small calculator
Now let's read a sum such as 12 + 30 + 5, and compute it.
The last query fails, because 1 + + 2 is not a sum.
This grammar doesn't work in the other direction. is/2 in braces needs known values, as chapter 7 showed. number_chars/2 needs either the number or the characters to be known. A grammar that computes is a parser only. The Markdown reader of chapters 17 and 18 is a parser only too, and chapter 19 writes the output with a second grammar.
Try it
- Add
-to the calculator. Note that10 - 2 - 3should be 5. What does your version give, and why? - Write a grammar
word//1that reads one or more lowercase letters, and gives the word as an atom. Use it to read'hello world'as[hello, world].