How do I specify a DCG for a valid number?

心已入冬 提交于 2019-12-07 16:21:35

问题


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?


回答1:


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.




回答2:


Here's an ABNF grammar for a numeric literal such as you might find in a computer language:

NUMERIC-CONSTANT = INTEGER-PART 0*1(FRACTIONAL-PART) 0*1(EXPONENT)

INTEGER-PART = 0*1(SIGN) 1*(DIGIT)

FRACTIONAL-PART = 0*1( DECIMAL-POINT 1*(DIGIT) )

EXPONENT = EXP 0*1(SIGN) 1*(DIGIT)

EXP = "E" / "e"

DECIMAL-POINT = "."

SIGN = "+" / "-"

DIGIT = "0" / "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9"

Since there's no left recursion in this grammar, this lends itself directly to a recursive descent parser, such as produced by a Prolog DCG:

numeric_constant --> integer , optional_fraction , optional_exponent .

integer --> optional_sign , digits .

optional_sign --> sign .
optional_sign --> [].

digits --> digit , digits .

optional_fraction --> fraction .
optional_fraction --> [].

fraction --> decimal_point , digits .

optional_exponent --> exponent .
optional_exponent --> [].

exponent --> exp , optional_sign , digits .

exp --> ['E'] .
exp --> ['e'] .

decimal_point --> ['.'] .

sign --> ['+'] .
sign --> ['-'] .

digit --> ['0'] .
digit --> ['1'] .
digit --> ['2'] .
digit --> ['3'] .
digit --> ['4'] .
digit --> ['5'] .
digit --> ['6'] .
digit --> ['7'] .
digit --> ['8'] .
digit --> ['9'] .


来源:https://stackoverflow.com/questions/32870994/how-do-i-specify-a-dcg-for-a-valid-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!