Did you know ... | Search Documentation: |

Rational number syntax |

As of version 8.1.22, SWI-Prolog supports rational numbers as a
primary citizen atomic data type if SWI-Prolog is compiled with the GMP
library. This can be tested using the bounded
Prolog flag. An atomic type also requires a syntax. Unfortunately there
are few options for adding rational numbers without breaking the ISO
standard.^{29ECLiPSe uses numerator_denominator.
This syntax conflicts with SWI-Prolog digit groups (see section
2.16.1.5) and does not have a recognised link to rational numbers.
The notation 1/3r and 1/3R have also been
proposed. The 1/3r is compatible to Ruby, but is hard to
parse due to the required look-ahead and not very natural. See also https://en.wikipedia.org/wiki/Rational_data_type.}

ECLiPSe and SWI-Prolog have agreed to define the canonical syntax for
rational numbers to be e.g., `1r3`

. In addition, ECLiPSe
accepts
`1_3`

and SWI-Prolog can be asked to accept `1/3`

using the module sensitive Prolog flag rational_syntax,
which has the values below. Note that write_canonical/1
always uses the compatible
`1r3`

syntax.

**natural**- This is the default mode where we ignore the ambiguity issue and follow
the most natural <
`integer`>/<`nonneg`> alternative. Here, <`integer`> follows the normal rules for Prolog decimal integers and <`nonneg`> does the same, but does not allows for a sign. Note that the parser translates a rational number to its canonical form which implies there are no common divisors in the resulting numerator and denominator. Examples of ration numbers are:1/2 1/2 2/4 1/2 1 000 000/33 000 1000/33 -3/5 -3/5 We expect very few programs to have text parsed into a rational number while a term was expected. Note that for rationals appearing in an arithmetic expression the only difference is that evaluation moves from runtime to compiletime. The utility list_rationals/0 may be used on a loaded program to check whether the program contains rational numbers inside clauses and thus may be subject to compatibility issues. If a term is intended this can be written as

`/(1,2)`

,`(1)/2`

,`1 / 2`

or some variation thereof. **compatibility**- Read and write rational numbers as e.g.,
`1r3`

. In other words, this adheres to the same rules as`natural`

above, but using the‘`r`

’instead of‘

’. Note that this may conflict with traditional Prolog as‘`/`

`r`

’can be defined as an infix operator. The same argument holds for`0x23`

and similar syntax for numbers that are part of the ISO standard.

While the syntax is controlled by the flag rational_syntax, behavior on integer division and exponentiation is controlled by the flag prefer_rationals. See section section 4.27.2.2 for arithmetic on rational numbers.

Tags are associated to your profile if you are logged in

Tags: