4

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.

Luka
  • 1,718
  • 3
  • 19
  • 29

1 Answers1

6

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:

maplist(number, L).

Or, recursively

allnumbers([]).
allnumbers([N|Ns]) :-
   number(N),
   allnumbers(Ns).

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:

numberatom(Atom) :-
   atom_chars(Atom, Chs),
    catch(number_chars(_, Chs), error(syntax_error(_),_), false).

Use numberatom/1 in place of number/1, So write a recurse rule or use maplist/2

3

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 like atom_to_term/3 and then apply one of the solutions above.

Community
  • 1
  • 1
false
  • 10,264
  • 13
  • 101
  • 209