Problems Solve each of the following problems using only the features of F# that
ID: 3670445 • Letter: P
Question
Problems
Solve each of the following problems using only the features of F# that we have discussed in class. In particular, you will not receive credit for solutions that use imperative programming constructs, or predefined (built-in) functions that make the solutions completely trivial. If you have doubts about what is allowed, check with me.
For each problem, write a single function definition without any nested functions. Your solutions do not need to be tail recursive.
Define a function called max that takes a list and returns the largest value in the list. You may assume that the list is not empty. Do not use the built-in List.max function.
Define a function called nth that takes an integer, n, and a list as arguments. The nth element of the list, indexed from 0, should be returned. You may assume that the list has at least one element.
Define a function called zip that takes a pair (tuple) of equal length lists as a single parameter and returns a list of pairs. The first pair should contain the first element of each list, the second pair contains the second element of each list, and so on.
Define a function called search that takes a boolean function, f, and a list as arguments and returns the zero-based index of the first element of the list, e, such that (f e) is true. If no such element exists, search should return -1.
Explanation / Answer
1) Max function to get max element of the list
let maxElement = 0
let elementList= [|1; 2; 3; 4; 11; 12; 13; 14|]
for j in 0 .. elementList.Length - 1 do
if maxElement < (elementList.[i]) then
maxElement <- elementList.[i]
printfn "%j" maxElement
2) Return nth element of the list
let rec nthElement list i =
match list with
| hd::x1 ->
if i = 0 then hd
else nthElement xl (i - 1)
| [] -> failWith "Index not found"
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.