I'm trying to learn prolog DCGs by creating a program that will recognize a valid floating point number. For example:
123.234 {true}
123..124 {false}
+123.123 {true}
-123.1 {true}
+-123.42 {false}
My code looks like this:
isFloat(Num) :- float(Num).
sign --> "", "+", "-".
float --> sign, number, ".", number.
number --> digit.
number --> digit, number.
digit --> [0,1,2,3,4,5,6,7,8,9].
For the most part it works, but sometimes I get an error output rather than false whenever there is something that doesn't fit the grammar.
output:
?- ['practice.pro'].
true.
?- isFloat(+12.234).
true.
?- isFloat(+12).
false.
?- isFloat(++12).
ERROR: Syntax error: Operator expected
ERROR: isFloat(+
ERROR: ** here **
ERROR: +12) .
?- isFloat(123.345..).
ERROR: Syntax error: Operator expected
ERROR: isFloat(123.34
ERROR: ** here **
ERROR: 5..) .
?- isFloat(+12.567).
true.
I assumed that if it doesn't fit the grammar correctly, the DCG would return false, but instead I get a syntax error if the passed in number doesn't fit the grammar. Could anyone explain what I'm doing wrong? Thanks.
Edit: Format question better.