Prolog: solving multi-variable arithmetics -


i having trouble writing prolog predicate returns variable values arithmetic.

for example, function should return x , y can equation: 12 = 3x + 2y.

currently code can work other way around:

foo(s,x,y) :-     s 3*x+2*y. 

any ideas?

depending on modeling domain you're in, use 1 of following:

  • integers

  • arbitrary precision rational numbers

  • limited-precision "real numbers", typically approximated floating-point values

  • boolean values


here's how can handle integers :

:- use_module(library(clpfd)).  foo(s,x,y) :-     s #= 3*x+2*y. 

let's @ sample queries!

first up: ground queries.

?- foo(1,23,-34). true.  ?- foo(1,23,-2). false. 

next up: queries one-variable.

 ?- foo(x,1,2). x = 7.  ?- foo(1,x,2). x = -1.  ?- foo(1,23,x). x = -34.  ?- foo(1,2,x). false. 

then, query 1 variable used in multiple places:

 ?- foo(x,x,x). x = 0. 

at last: more general queries.

?- foo(s,x,2). s#=3*x+4.  ?- foo(s,x,y). s#=3*x+2*y. 

for arbitrary-precision rational numbers, use :

:- use_module(library(clpq)).  ?- foo(x,x,x). x = 0.  ?- foo(1,2,x).          % similar query failed clp(fd) x = -5 rdiv 2.          % arbitrary-precision solution  ?- foo(s,x,y). {y=1 rdiv 2*s-3 rdiv 2*x}. 

for relations on floating-point numbers, use :

:- use_module(library(clpr)).  foo(s,x,y) :-     { s = 3*x+2*y }. 

sample queries:

?- foo(1,2,x).          % similar query failed clp(fd) x = -2.5 ;              % , had arbitrary-precision solution clp(q) false.  ?- foo(x,x,x). x = 0.0 ; false. 

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -