Reputation:
How can I calculate the sum of two fractions in Prolog. Lets name the function fracsum(X,Y,Z)
with x+y=z
(x and y fractions to give z also as fraction).
Some examples : fracsum(1/9,1/9,Z)
results Z=2/9
or fracsum(5/9,1/9,Z)
results Z=2/3
(also get the lowest divided fraction, instead of 6/9 get 2/3).
Since I'm a beginner in Prolog, any help would be useful.
Upvotes: 1
Views: 735
Reputation:
If you have SWI-Prolog you don't have to do anything special, just use rdiv
to make rational numbers, like this:
?- Z is 1 rdiv 9 + 1 rdiv 9.
Z = 2 rdiv 9.
?- Z is 5 rdiv 9 + 1 rdiv 9.
Z = 2 rdiv 3.
You might wonder but how do you make 1/9
into 1 rdiv 9
but this is quite easy, here is how you can make a small predicate that does it for just one rational, like @lurker already tried to explain in the comment to your question:
frac_rational(A/B, A rdiv B).
If you define this relation than you can then make an SWI-Prolog rational out of a fraction:
?- frac_rational(1/9, Rational).
Rational = 1 rdiv 9.
And if you are wondering "but what is a fraction?" then you can see that it is nothing special just a term:
?- write_canonical(1/9).
/(1,9)
true.
but of course /
is operator and this is why you can write 1/9
and don't have to always write /(1,9)
:
?- current_op(Precedence, Type, /).
Precedence = 400,
Type = yfx.
But but but if you don't have SWI-Prolog or maybe for didactical reasons you want to do the rational arithmetic on your own than this is not going to be enough you would have at the very least figure out how you can add fractions with different denominators and how you simplify fractions, and this is not a Prolog question but a simple math question that for didactical reasons you should answer on your own before you ask how to do it in Prolog.
Your Prolog might also have a library for CLP(Q) then you can amaze your teacher by showing this:
?- use_module(library(clpq)).
true.
?- {1/9 + X = 2/3}.
X = 5 rdiv 9.
But maybe this is not what you are asking.
Upvotes: 5