You're given the type length = In of float | Cm of float. Write an OCaml function addlen(x,y) that adds two lengths. If x is in inches, the sum should be in inches; if x is in centimeters, the sum should be in centimeters.
Here is the complete OCaml Code for the addlen function. I have added comments for a better understanding of the same:
let addlen(x,y) = match (x,y) with
| (In(a), In(b)) -> In(a +. b) (* Answer is in Inches *)
| (In(a), Cm(b)) -> In(a +. (b /. 2.54)) (* Answer is in Inches *)
| (Cm(a), Cm(b)) -> Cm(a +. b) (* Answer is in cms *)
| (Cm(a), In(b)) -> Cm(a +. (b *. 2.54));; (* Answer is in cms *)
You can comment below the answer in case of any doubts and I will be happy to help.
Please give a thumbs up if the answer could be of help!
All the best!
Get Answers For Free
Most questions answered within 1 hours.