user2962883
user2962883

Reputation: 57

Prolog: Variable with multiple values

I'm trying to implement a program that takes a variable with multiple values and evaluates all the values. For instance:

foo(X,R) :-
  X > 2,
  Z is R + 1,
  R = Z.

This program might not be valid, but it will help me ask the question regardless.

My question: If X has multiple values, how would I increment the counter for each value X > 2?

Upvotes: 1

Views: 1178

Answers (1)

Wouter Beek
Wouter Beek

Reputation: 3407

In order to instantiate X to increasingly larger integers you can use the following:

?- between(0, inf, X).
X = 0 ;
X = 1 ;
X = 2 ;
X = 3 ;
X = 4 ;
<ETC.>

PS1: Notice that you have to instantiate R as well since it is used in the arithmetic expression Z is R + 1.

PS2: Notice that your program fails for all instantiations of X and R since R =\= R + 1 for finite R. The for instance means that the following query will not terminate:

?- between(0, inf, X), foo(X, 1).

Alternatively, the program can be rewritten in library CLP(FD) (created by Markus Triska):

:- use_module(library(clpfd)).

foo(X,R):-
  X #> 2,
  Z #= R + 1,
  R #= Z.

Upvotes: 1

Related Questions