Arithmetic Prolog Syntax

How to define a as integer / float number?

I want to find the results a+b+c+d=10 , where a,b,c,d is an integer and >=0 .

+4
source share
3 answers

Here is a simple, modern, clean Prolog, non-CLP library:

 range(X):- member(X,[0,1,2,3,4,5,6,7,8,9,10]). ten(A,B,C,D):- range(A), range(B), range(C), range(D), 10 =:= A + B + C + D. 
+4
source

using SWI-Prolog you can use the CLP library (FD)

 1 ?- use_module(library(clpfd)). % library(error) compiled into error 0.00 sec, 9,764 bytes % library(clpfd) compiled into clpfd 0.05 sec, 227,496 bytes true. 2 ?- Vars=[A,B,C,D],Vars ins 0..10,sum(Vars,#=,10),label(Vars). Vars = [0, 0, 0, 10], A = 0, B = 0, C = 0, D = 10 ; Vars = [0, 0, 1, 9], A = 0, B = 0, C = 1, D = 9 ; Vars = [0, 0, 2, 8], A = 0, B = 0, C = 2, D = 8 ; Vars = [0, 0, 3, 7], A = 0, B = 0, C = 3, D = 7 ; ... 
+5
source

Here is the GNU-Prolog portion of the code with the solution limiting to the final domains:

 $ gprolog | ?- [user]. compiling user for byte code... ten(A,B,C,D) :- fd_domain([A,B,C,D],0,9999999), 10 #= A + B + C + D. 

Ctrl + D

 | ?- ten(A,B,C,D), fd_labeling([A,B,C,D]). 

As you can see, it solves the problem of large ranges , for example, 0-9999999

 A = 0 B = 0 C = 0 D = 10 ? ; A = 0 B = 0 C = 1 D = 9 ? ; A = 0 B = 0 C = 2 D = 8 ? ; ... 

PS Thanks for Przemysław Kobylański for his blog with clear, very nice Prolog examples , where I found inspirational examples.

PPS When playing with finite domains, you can use fd_set_vector_max / 1 . In the above case, this is not necessary, but depending on the restriction it may be useful - in more detail, when Gnu-Prolog runs on ranges, when on vectors of possible values can be found in the manual "The ultimate domain resolver and built-in predicates - Introduction"

+2
source

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


All Articles