I am doing this assignment for homework and I've been stuck on this problem for like 3 hours. I just emailed the professor, but haven't heard back from them yet, so I decided to ask here as well.
We are assigned to write various functions, such as finding the gcd of a fraction in the format (14, 2) where 14 is the numerator and 2 is the denominator.
I have the functions gcd, simplify, add, and times done, but am stuck on addAll.
addAll is supposed to take a list of fractions described as coordinate pairs and sum them all up and simplify it and return the answer as one fraction formated as such (numerator, denominator).
Currently, my addAll function adds them all up and returns the fraction formatted correctly, but it doesn't simplify it. I already have the simplify function written, but whenever I try to call simplify around my addAll recursive call, I get errors.
My current code is this:
fun addAll L = if L = [] then [(0, 1)] else if tl L = nil then L else addAll(
[
( ((#1 (hd L)) * (#2 (hd (tl L)))) + (#1 (hd (tl L))) * (#2 (hd L)), (#2 (hd L))*(#2 (hd (tl L))) )
]
@
(tl (tl L))
);
(*
a = (#1 (hd L))
b = (#2 (hd L))
c = (#1 (hd (tl L)))
d = (#2 (hd (tl L)))
*)
I was trying to solve the problem by doing this:
fun addAll L = if L = [] then [(0, 1)] else if tl L = nil then L else simplify(addAll(
[
( ((#1 (hd L)) * (#2 (hd (tl L)))) + (#1 (hd (tl L))) * (#2 (hd L)), (#2 (hd L))*(#2 (hd (tl L))) )
]
@
(tl (tl L))
));
(*
a = (#1 (hd L))
b = (#2 (hd L))
c = (#1 (hd (tl L)))
d = (#2 (hd (tl L)))
*)
but I am getting errors.
Any help would be appreciated.
Thanks.
Also, I will attach my whole code that runs in sml if it helps...
Here is all my code for the assignment:
fun gcd (a, b) =
if b = 0 then a else gcd(b, a mod b);
fun simplify (a, b) = if gcd(a, b) < 2 then (a, b) else ((a div gcd(a, b)), (b div gcd(a, b)));
fun add (a,b) (c,d) = simplify((a*d + c*b), b*d);
fun times (a,b) (c,d) = simplify( (a*c), (b*d) );
fun addAll L = if L = [] then [(0, 1)] else if tl L = nil then L else addAll(
[
( ((#1 (hd L)) * (#2 (hd (tl L)))) + (#1 (hd (tl L))) * (#2 (hd L)), (#2 (hd L))*(#2 (hd (tl L))) )
]
@
(tl (tl L))
);
(*
a = (#1 (hd L))
b = (#2 (hd L))
c = (#1 (hd (tl L)))
d = (#2 (hd (tl L)))
*)
(*fun timesAll L = if L = [] then [(1, 1)] else if tl L = nil then L else timesAll();*)
fun lessThan (a, b) (c, d) = if ((real a) / (real b)) < ((real c) / (real d)) then true else false;