Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Using F# 1) A fraction like 2/3 can be represented in F# as a pair of type int * int. Define infix operators .+ and

Using F#

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);; val it : int * int = (5, 6) > (1,2) .+ (2,3) .* (3,7);; val it : int * int = (11, 14) 

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 precedences 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, which can be implemented in F# as follows:

 let rec gcd = function | (a,0) -> a | (a,b) -> gcd (b, a % b) 

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 takes just one line of code, using List.map and List.rev.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Reshaping Accounting And Management Control Systems

Authors: Katia Corsi, Nicola Giuseppe Castellano, Rita Lamboglia, Daniela Mancini

1st Edition

3319495372, 978-3319495378

Students also viewed these Databases questions