Search code examples
listprologswi-prolog

Check if list is made up by numbers only - Prolog


I need to write a predicate that returns true if a given list contains only numbers in Prolog. Example:

?- isDigit(['1', '2', '3']).
true

This is the code I've made so far:

isDigit(X) :-  digit(X).
isDigit([X | Xs]) :- digit(X), isDigit(Xs).

digit(1).
digit(2).
digit(3).
digit(4).
digit(5).
digit(6).
digit(7).
digit(8).
digit(9).
digit(0).

It returns false every time and i don't get the reason why.

Thank you


Solution

  • I found two issues with your code. First:

    isDigit(X) :-  digit(X).
    

    In your case the argument of isDigit/1 is a list, and you want to ask for the elements of this list. For handling the only element of a list write it like this:

    isDigit([X]) :-  digit(X).
    

    Second: 1 and '1' are different. Try this as query:

    ?- isDigit([1, 2, 3]).
    

    Tested with SWISH.