Number Parsing in Prolog

Our first example demonstrates how to parse numbers from strings in Prolog. This is a common task in many programs.

% The built-in library 'library(readutil)' provides number parsing functionality
:- use_module(library(readutil)).

main :-
    % With read_number_from_atom/2, we can parse floating-point numbers
    atom_number('1.234', F),
    writeln(F),

    % For parsing integers, we can use number_codes/2
    number_codes(I, "123"),
    writeln(I),

    % Prolog recognizes hexadecimal numbers with the 0x prefix
    number_codes(D, "0x1c8"),
    writeln(D),

    % For unsigned integers, we can use the same method
    number_codes(U, "789"),
    writeln(U),

    % atom_number/2 is a convenience predicate for basic number parsing
    atom_number('135', K),
    writeln(K),

    % Parsing functions fail on bad input
    (   atom_number('wat', _)
    ->  writeln('Parsing succeeded')
    ;   writeln('Parsing failed')
    ).

% To run the program
:- main.

To run the program, save it as number_parsing.pl and use the Prolog interpreter:

$ swipl -s number_parsing.pl
1.234
123
456
789
135
Parsing failed

In Prolog, number parsing is handled differently compared to some other languages:

  1. atom_number/2 is used to parse both floating-point numbers and integers.
  2. number_codes/2 can be used to parse integers, including hexadecimal numbers.
  3. There’s no separate function for parsing unsigned integers; Prolog uses arbitrary-precision integers.
  4. Instead of returning an error, parsing predicates in Prolog typically fail when given invalid input.

Next, we’ll look at another common parsing task: URLs.