更新时间:2023-11-29 16:22:10
我给你一个描述自然数字的代码示例:
:- set_prolog_flag(double_quotes, chars).natural_number(N) --> number_(Cs), { number_codes(N, Cs) }.number_([D|Ds]) --> digit(D), number_(Ds).number_([D]) --> 数字(D).digit(D) --> [D], { char_type(D, digit) }.示例用法:
?- 短语(natural_number(N), "123").N = 123 ;错误的.
我将此作为练习推广到其他数字.
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?
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.