# Seminar 1 Tasks Q1. Declare a function g: int -&gt; int, whe...

## Question

Q1. Declare a function g: int -> int, where g(n) = n + 4.

Q2. Declare a function h: float * float -> float, where h(x, y) = sqrt(x2 + y 2)

Q3.Please watch the video in Robert C. Martin – Functional Programming: What? Why? When? and answer the following questions (you need to do some
extra readings as well as find resources from Internet):
(1) What is the main difference between Imperative Programming and Functional Programming?
(2) How do you write a loop with stateless way? Please clarify your answer by given an example.
(3) Could you list the advantages and disadvantages of Functional programming? Why is FP likely to become more popular in future by considering its pros and cons?
(4) What is the solution for concurrency programming in imperative programming languages? Could you compare it with the way in FP?

1. Declare a function with a tuple of name and age as input and return a string “The xxx is yyy years old”, here xxx and yyy are the input arguments.
2. Please debug the following code:
let add (a:string) (b:int) = a + b
3. Analyse the following function:
let toTriple a b c = (a, b, c);;
What are the data type of a, b and c? Give a couple of example to use the function.
4. Explain what is the difference between List and Array in F#? Please debug the following code:
let simpleList =["element1";"element2";"element3";"element4"]
simpleList.[0] <- "revised1"
System.Console.WriteLine(sprintf "%A" simpleList)

Declare a function f s1 s2 n that builds a string with n lines alternating between s1 and s2.
For example: f "ab" "cd" 4 = "ab\ncd\nab\ncd" and f "XO" "OX" 3 = "XO\nOX\nXO". Note that \n is the escape sequence for the newline character. Give the type of the function.
5. If Q2 and Q3 in this section are implemented with imperative way, can you think how they can be implemented with Functional Programming (FP) way and explain the difference.
If they are implemented in FP way, please explain the difference with the imperative way as well.
6. Declare a function to determine if a triangle is equilateral, isosceles, or scalene. An equilateral triangle has all three sides the same length. An isosceles triangle has at least two sides the same length. (It is sometimes specified as having exactly two sides the same length, but for the purposes of this exercise we'll say at least two.) A scalene triangle has all sides of different lengths.
7. Declare a recursion function which reverses a list with n elements.
8. The Fibonacci sequence is a series of numbers where a number is found by adding up the two numbers before it. Starting with 0 and 1, the sequence goes 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so forth. Written as a rule, the expression is xn = xn-1 + xn-2. Please write a recursive function to calculate the Fibonacci sequence.

9. Please explain what the following function performs (here p is a function to check
whether an input value is even):
let rec g1 p = function
| x::xs when p x -> x :: g1 p xs
| _ -> [];;

Part 1. Understand the concept
1. Create a Customer type with three attributes: Id:int, Credit:float, PurchaseFrequence:int.
2. Declare a function which input is a Customer and an amount to buy an item, if the credit is larger than the amount, return a Customer with new Credit which reduces the amount from the old Credit. Otherwise return the same Customer record.
3. Declare a function to check the PurchaseFrequence, if the number is larger than 100, return a customer with increasing credit £1000, else if the number is larger than 50, return a customer with increasing credit £500, otherwise increasing credit 200.
4. Declare a Color type with three attributes: R:int, G:int, B:int. and declare a function which has two Color instances as input and return the Euclidean Distance of the two Colors (it means the square root of (C1.R-C2.R)2 + (C1.G-C2.G)2) + (C1.B-C2.B)2 ).
5. Declare a function to take the output from a function f(y) = y + 3 into another function g(x) = x2 as the input.
6. In the lecture slides, you have seen that function composition allows you to bind a function to a sequential of functions like:
let function1 x = x+1
let function2 x = x*2
let h = function1 >> function2
let result = h 100
Could you use forward pipeline to replace the function composition to get the same result?

Part 2. Practice
1. Assume you have declared a function f x y = x +y. Please declare another function mixMap so that
mixMap f [x0; x1; : : : ; xm] [y0; y1; : : : ; ym] = [f(x0; y0); f(x1; y1); : : : ; f(xm; ym)]. (Hint: please check the List.map2 function).

2. Assume you have a binary search tree which is declared as:

type Tree<'a> =
| Empty
| Node of value: 'a * left: Tree<'a> * right: Tree<'a>

Please provide a couple of examples of using the following functions and explain what the following functions do and explain why.

let rec findInOrderPredecessor (tree : Tree<'a>) =
match tree with
| Empty -> Empty
| Node (_, _, Empty) -> tree
| Node (_, _, right) -> findInOrderPredecessor right

let rec dosth value (tree : Tree<'a>) =
match tree with
| Empty -> Empty
| Node (value', left, right) when value < value' ->
let left' = dosth value left
Node (value', left', right)
| Node (value', left, right) when value > value' ->
let right' = dosth value right
Node (value', left, right')
| Node (_, Empty, Empty) ->Empty
| Node (_, left, Empty) ->left
| Node (_, Empty, right) ->right
| Node (_, left, right) ->
let (Node(value', _, _)) = findInOrderPredecessor left
let left' = dosth value' left
Node (value', left', right)

3. Consider the following F# declarations of a type for binary trees and a binary tree t:

type Tree<’a> = Lf | Br of Tree<’a> * ’a * Tree<’a>;;
let t = Br(Br(Br(Lf,1,Lf),2,Br(Lf,3,Lf)),4,Br(Br(Lf,5,Lf),6,Br(Lf,7,Lf)));;

An illustration of the tree t is given in the above figure. The right part of the figure shows the reflection of t, that is, a mirror image of t formed by exchanging the left and right subtrees all the way down. Declare a function reflect that can reflect a tree as described above.

Part 1. Understand the concept

1. Assume that you have a function to compute the sum of the norm of a vector: let norm(x:float,y:float) = sqrt(x*x+y*y);;
Please use the List.fold to accumulate the sum of the norms of a list of vectors (Vector can be expressed in a tuple (x,y)).

2. If a f function is defined as f(n) = n*3-2, please define a g function which will take f and a tuple (x,y) as input and return a tuple of (f(x), f(y)).

3. Assume you have a list of tuple Student(Name, Age), for example [(“John”, 18);(“Kay”, 21) ….], can you use List.filter to get a list with all the students who are older than 20.

4. Given the following recursive function, please use an accumulating parameter to make a tail-recursive variant of the function. Let rec f n = function
| 0 -> 1
| k when k>0 -> n * (f n (k-1))
| _ -> failwith "illegal argument";;

Part 2. Practice

5. Assume you have the following defined type:
type Name = string;;
type Score = int;;
type Result = Name * Score;;

(a) Declare a function legalResults: Result list -> bool that checks whether all   score in a list of results are legal (Hint: you can use List.fold and List.map).

(b) Declare a function maxScore that extracts the best score (largest value) in a non-empty list of results (Hint: you can use List.fold and List.map).

(c) Declare a function best: Result list -> Result that extracts the best result from a non-empty list of results. An arbitrary result with the best score can be chosen if there are more than one.

(d) Declare a function averageStudents: Result list -> float that finds the average score for a non-empty list of results.

6. Consider the following declaration:
let rec f i = function
| [] -> []
| x::xs -> (x+i)::f (i*i) xs;;
Make a tail-recursive variant of f using an accumulating parameter.

## Solution Preview

These solutions may offer step-by-step problem-solving explanations or good writing examples that include modern styles of formatting and construction of bibliographies out of text citations and references. Students may use these solutions for personal skill-building and practice. Unethical use is strictly forbidden.

Q1 Declare a function g: int -> int, where g(n) = n + 4.

let g n = n + 4

Q2. Declare a function h: float * float -> float, where h(x, y) = sqrt(x2 + y 2)
let h ((x:float), (y:float)) = sqrt (x*x + y*y)

Q3. Please watch the video in Robert C. Martin – Functional Programming: What? Why? When? https://vimeo.com/97514630 and answer the following questions (you need to do some extra readings as well as find resources from Internet):
(1) What is the main difference between Imperative Programming and Functional Programming?
The main difference between IP and FP is IP is stateful and FP is stateless. In IP, a program is a list steps that needs to be executed. And the order of execution is always matters. So, state of the program needs to be tracked and change of status cause to change the flow of the program. But in FP, functions are used to gain and transform data and those functions are stateless. Return value of a function is only defend on its inputs.
(2) How do you write a loop with stateless way? Please clarify your answer by given an example.
Functional programming does not use loops because it needs to keep mutable states, recursion is used instead.
Following function of calculating factorial is implemented using recursion in stateless way....

By purchasing this solution you'll be able to access the following files:
Solution.zip.

\$115.00
for this solution

PayPal, G Pay, ApplePay, Amazon Pay, and all major credit cards accepted.

### Find A Tutor

View available Computer Science - Other Tutors

Get College Homework Help.

Are you sure you don't want to upload any files?

Fast tutor response requires as much info as possible.