Integer generation <limit

I am trying to generate all integers (natural numbers) that are less than the limit, say 10. I have a predicate nat(X)that produces all numbers from 0 to infinity.

Now my problem is: if I do this:

nat10(X) :- nat(X), X =< 10.

This will never stop as he tries to find other solutions with nat(X)ad infinitum.

I need a construct that would allow me to abort the entire predicate if one subgoal fails. How should I do it?

+4
source share
2 answers

Depending on the task at hand, you may need to program the finite domain constraint logic (CLPFD).

Prolog , X > 10. nat10/1 , :

nat10(X) :- nat(X), ( X > 10 -> !, fail ; true ).

, X > 10, (!), nat(X) ( , 10 ), fail. (true).

| ?- nat10(X).

X = 1 ? ;

X = 2 ? ;

...

X = 9 ? ;

X = 10 ? ;

(3 ms) no
| ?-
+4

, !

:- use_module(library(clpfd)).

:

nat10(X) :-
   X in 0..10,
   indomain(X).
+3

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


All Articles