Lesson goal: Add fractions using Prolog

Previous: Counting in Prolog | Home | Next: Divisibility rules

Let's write some Prolog that will add fractions together. This takes a bit of logic, as you may remember from your math class.

Suppose you have two fractions $N_1/D_1$ and $N_2/D_2$, where $N$ means numerator and $D$ means denominator. The $1$ and $2$ refer to fractions $1$ and $2$ to add together, so we'd like to find $N_1/D_1+N_2/D_2$.

You probably remember the plan:
  • If the denominators are the same, or $D_1=D_2$, then the sum will have this denominator, with the two numerators added together. This means $N_{sum}=N_1+N_1$ and $D_{sum}=D_1$ (or $D_2$). The answer will be $N_{sum}/D_{sum}$.

  • If the denominators are different, or $D_1\ne D_2$, we'll have to find a common denominator $D_{sum}$, which is $D_{sum}=D_1\times D_2$. The numerator of fraction 1 will become $N'_1=N_1\times D_2$, and the numerator of fraction 2 will become $N'_2=N_2\times D_1$. Now, the numerator of the sum will be the sum of the new numerators, or $N_{sum}=N_1'+N_2'$. Once again, the answer will be $N_{sum}/D_{sum}$.
As an example, if the denominators are the same, as in $1/5+2/5$. The answer will be $3/5$. If the demoninators are different, like $2/3+1/4$, the $2/3$ will become $8/12$ and the $1/4$ will become $3/12$. The answer will be $8/12+3/12=11/12$.

As for Prolog, we'd like the goal to be something like add(1,5,2,5,Nsum,Dsum). for which we'd like Prolog to find Nsum to be 3 and Dsum to be 5. For something like add(2,3,1,4,Nsum,Dsum)., we'd like Prolog to find Nsum to be 11 and Dsum to be 12.
add(N1,D,N2,D,Nsum,D):- Nsum is N1 + N2.
add(N1,D1,N2,D2,Nsum,Dsum)
Move the mouse over a dotted box for more information.

Now you try. Finish the code for the fractions with different denominators.

Type your code here:


See your results here: