Search code examples
prologdcg

How do I specify a DCG for a valid number?


I'm trying to specify a DCG for a valid number that would be used like so:

value(Number) --> valid_number(Number).

Basically checking if a specified value is numeric, (it could also be a variable, so it's necessary to check).

I don't know how to build this valid_number DCG/predicate though.

Right now I just have:

valid_number('1') --> ['1'].
valid_number('2') --> ['2'].
...

Which works but it obviously terrible. Trying something like:

valid_number(Number) --> { integer(Number), Number = Number }.

Which both doesn't work and admittedly looks pretty gross as well (I'm sorry, very new to Prolog and trying to learn best practices).

How would I go about building this DCG/predicate that validates whether or not it's a number?


Solution

  • I give you a code sample that describes natural numbers:

    :- set_prolog_flag(double_quotes, chars).
    
    natural_number(N) --> number_(Cs), { number_codes(N, Cs) }.
    
    number_([D|Ds]) --> digit(D), number_(Ds).
    number_([D])    --> digit(D).
    
    digit(D) --> [D], { char_type(D, digit) }.
    

    Example usage:

    ?- phrase(natural_number(N), "123").
    N = 123 ;
    false.
    

    I leave generalizing this to other numbers as an exercise.