Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solutions for sum in Prolog

Tags:

prolog

I'm an absolute beginner to prolog. I've just read a basic tutorial and tried to solve a quick problem on my own. The problem is this, find possible number combinations that lead to a sum. I'm expecting something like this:

sum(A,B,11).

This should result in values for A and B that would sum them upto 10.

My initial code was this:

sum(A,B,C):-
    C is A + B.

But I do not get any results with this. I get the following.

ERROR: Arguments are not sufficiently instantiated
ERROR: In:
ERROR:    [9] 11 is _3302+_3304
ERROR:    [7] <user>
ERROR: 
ERROR: Note: some frames are missing due to last-call optimization.
ERROR: Re-run your program in debug mode (:- debug.) to get more detail.

What am I missing in my understanding of Prolog?

like image 220
Nikhil Vandanapu Avatar asked Dec 12 '25 01:12

Nikhil Vandanapu


1 Answers

The standard is/2 predicate requires an evaluable arithmetic expression for second argument. Thus, in your case, you will need to generate possible values for A and B so that A + B can be computed. To make it practical, you will need to restrict the range of possible values. For example:

?- between(1,7,A), between(1,7,B), sum(A,B,11).
A = 4,
B = 7 ;
A = 5,
B = 6 ;
A = 6,
B = 5 ;
A = 7,
B = 4 ;
false.

As you progress on your learning of Prolog, you may eventually be interested in learning about constraint solvers.

like image 191
Paulo Moura Avatar answered Dec 14 '25 16:12

Paulo Moura



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!