Search code examples
prologclpfd

Retrieving all the numbers from a given interval in Prolog


I am new into the world of Prolog, and I would like to write a rule that return all the elements in a specific range.

I intend to do something like

Ex:

foo(X, Low, High) :- X > Low, X < High.

And when I type foo(X, 2, 5), it should return 3, and then 4.

It seems that my approach is wrong, and I would like to know which is the correct way to do it.


Solution

  • When written like that, Prolog doesn't know what kind of numbers do you want (and whether you even want numbers).

    One way to implement this would be:

    range(X, L, H) :- X is L + 1, X < H.
    range(X, L, H) :- L1 is L + 1, L1 < H, range(X, L1, H).