Can someone help me answer the following questions using pure F# functional prog
ID: 3888146 • Letter: C
Question
Can someone help me answer the following questions using pure F# functional programming code and provide explanations please so confused on how to write in F.
(no mutable variables, no loops, etc.). Develop your F# script file that contains solutions of all problems, using Microsoft Visual Studio 2017.
Document your program well so that the reader can read and understand it quickly. You are free to define auxiliary functions to assist you in solving some of the given problems. Every function defined should be very well documented.
1.
A fraction like 2/3 can be represented in F# as a pair of type int * int. Define infix operators .+ and .* to do addition and multiplication of fractions:
> (1,2) .+ (1,3);; // (1/2) + (2/3) = (5/6)
val it : int * int = (5, 6)
> (1,2) .+ (2,3) .* (3,7);; // (1/2) + (2/3) * (3/7) = (11/14)
val it : int * int = (11, 14)
> (1,8) .+ (3,8);; // (1/8) + (3/8) = (1/2)
Val: it:int * int = (1, 2)
Note that the F# syntax for defining such an infix operator looks like this:
let (.+) (a,b) (c,d) = ...
Also note that .+ and .* get the same precedence as + and *, respectively, which is why the second example above gives the result it does.
Finally, note that your functions should always return fractions in lowest terms. To implement this, you will need an auxiliary function to calculate the gcd (greatest common divisor) of the numerator and the denominator; this can be done very efficiently using Euclid's algorithm:
gcd (x, y) = x; if y=0
= gcd (y, x mod y); if y>0
2.
Write an F# function revlists xs that takes a list of lists xs and reverses all the sub-lists:
> revlists [[0;1;1];[3;2];[];[5]];;
val it : int list list = [[1; 1; 0]; [2; 3]; []; [5]]
Hint: This is trivial using List.map.
Explanation / Answer
Hi, You are supposed to ask two seperate questions for this, since the 2nd one is very easy, i am going to solve it here, but please refrain from doing this next time.
1.
let (.+)(x, y)(p, q) = /* defining the function */
let a = (x*q)+(y*p) .* performing the basic fraction addition */
let b = (y*q)
let c = gcd(a,b) // reducing the result to the lowest form
(a/b,b/c);;
similarly for *
let (.*)(x, y)(p, q) =
let a = (x*p)
let b = (y*q)
let c = gcd(a,b)
(a/c,b/c);;
2. there is a method in List.map which we can use for this,
let reverselists l = List.map (fun x -> List.rev x) l;; /* all the sublists are reversed */
Thumbs up if this was helpful, otherwise let me know in comments, good day.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.