Asian_Ninja1
Asian_Ninja1

Reputation: 5

How do I use an "either or" with a math function in Prolog?

I'm a total Prolog newbie and I'm currently building a KenKen solver in Prolog and I'm a little stuck right how.

In KenKen, there are "cages" where the numbers have to (add || sub || mult || div) to equal the required total of the cage. For example, a cage must divide two numbers (X, Y) to be equal to 2. However, X and Y can be (X/Y) or (Y/X) ; it does not matter what order.

I'm trying to figure out how to make it possible for Prolog to check both possibilities as an "either or".

Here's the code I've tried:

Cage2 is (X/Y), Cage2 =:= 2,
Cage2 is (Y/X), Cage2 =:= 2,

and also tried:

Cage2 is (X/Y), (Y/X), Cage2 =:= 2,

But this code now only reads the first one and I can't get it to read the second one.

Upvotes: 0

Views: 460

Answers (1)

Daniel Lyons
Daniel Lyons

Reputation: 22803

So, your first block cannot succeed because Cage2 is (X/Y), ... Cage2 is (Y/X) can only succeed if Cage2 is the same value both times. You are trying to reassign Cage2 here, and Prolog simply doesn't work that way. Also, the comma in Prolog means "and", so you have said all four of those ideas have to be true for the query to be true, and there is no pair of numbers (X,Y) such that both X/Y and Y/X = 2.

Your second block cannot succeed because (Y/X) is just hanging out there not doing anything, which will turn out to be a syntax error.

What you need is the operator ;, which is how you write "or" in Prolog. To do this in a single clause you need something like:

(X/Y =:= 2; Y/X =:= 2).

If you had two clauses it would be even easier:

foo(X, Y) :- X / Y =:= 2.
foo(X, Y) :- Y / X =:= 2.

In the second case you're getting an implicit "or" from having two clauses. This will generate a choice point for you, which you may not want, but isn't really that harmful.

Upvotes: 1

Related Questions