Check if the value is a number in the prolog manually

How to check if a given value is a number in Prolog, but without using built-in predicates like number ?

Say I have a list of [a, 1, 2, 3] . I need a way to check if every item in this list is a number. The only part of the problem that bothers me is how to check and not use the number predicate.

The reason I'm trying to figure this out is because I have a college assignment where he specifically said that he does not use any built-in predicates.

+4
source share
1 answer

To solve this problem, you need a built-in predicate - if you do not list all the numbers explicitly (which is impractical, since there are infinitely many of them).

1

The easiest way:

 maplist(number, L). 

Or, recursively

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

2

In the commentary, you say that "meaning is given as an atom." This may mean that you get either [a, '1', '2'] or '[a, 1, 2] `. I guess the first one. And here you will need a built-in predicate to parse the name. Based on the errors of ISO-Prolog, we write:

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

Use numberatom/1 instead of number/1 , so write a recursion rule or use maplist/2

3

You might want to write a grammar instead of a catch... target. Recently there are many such definitions, you can look at this question .

4

If all the "value" is specified as an atom, you will need atom_chars/2 again, or you may need some specific solution, for example atom_to_term/3 , and then apply one of the above solutions.

+4
source

Source: https://habr.com/ru/post/1444493/


All Articles