Prologue how to use math operation

I am new to prolog programming, I use swi prolog. Now I am overshadowed by some mathematical problems.

since we know the predicate: A is 3+3.works well, the answer A=6.

but if I want to find two digits (A and B) from 0 ~ 9, then a + b = 6 6 is A+Bdoes not work. so I want to know if there is an easy way to do this? And what if I want to find 3 digits (A, B and C) from 0 ~ 9, that A + B + C = 13, how to do it?

+4
source share
3 answers

an easier way that works in every Prolog implementation: declare the predicate digit / 1 (the notation predicate / N means that the predicate has N arguments)

digit(D) :- member(D, [0,1,2,3,4,5,6,7,8,9]).

then you can ask

?- digit(A),digit(B),6 is A+B.
A = 0,
B = 6 ;
A = 1,
B = 5 ;
...

since the sum is symmetric, maybe you want to reduce the duplicate solution with

?- digit(A),digit(B),A=<B,6 is A+B.

Using the library (clpfd), you can avoid the definition of the digit / 1 predicate and get a lot of functionality:

?- [library(clpfd)].
true.

?- [A,B,C] ins 0..9, A+B+C #= 13, label([A,B,C]).
A = 0,
B = 4,
C = 9 ;
A = 0,
B = 5,
C = 8 
...

Note that incognite may now remain to the left of the "destination" ...

+2
source

My advice to you as a Prolog novice:

  • First of all, first!

  • Use clpfd! . You can start right now by reading the tag information section of the tag .

  • .pl :

    :- use_module(library(clpfd)).
  • clpfd , Prolog : . . .

  • , clpfd .

  • , , - 1970 (is)/2!

    ? (is)/2 - , .

+2

, . , , . , , , 0 9, . , , :

add3 (A, B, C, SUM): - SUM - A + B + C.

. . : SWI-Prolog

Constraint. http://www.swi-prolog.org/man/clpqr.html

+1

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


All Articles