How to check if the given value is a number in Prolog without using built-in predicates like number?
Let’s say I have a list [a, 1, 2, 3]. I need a way to check if every element within this list is a number. The only part of the problem that bothers me is how to do the check itself without using the number predicate.
The reason why I’m trying to figure this out is that I’ve got a college assignment where it’s specifically said not to use any of the built-in predicates.
You need some built-in predicate to solve this problem – unless you enumerate all numbers explicitly (which is not practical since there are infinitely many of them).
1
The most straight-forward would be:
Or, recursively
2
In a comment you say that “the value is given as an atom”. That could mean that you get either [a, ‘1’, ‘2’] or ‘[a, 1, 2]`. I assume the first. Here again, you need a built-in predicate to analyze the name. Relying on ISO-Prolog’s errors we write:
Use
numberatom/1in place ofnumber/1, So write a recurse rule or usemaplist/23
You might want to write a grammar instead of the
catch...goal. There have been many such definitions recently, you may look at this question.4
If the entire “value” is given as an atom, you will need again
atom_chars/2or you might want some implementation specific solution likeatom_to_term/3and then apply one of the solutions above.