Question: Using language F#. Full and complete answer in order to get full credit please. Do not copy-paste from diferent site. Thank you 1)Two powerful List
Using language F#. Full and complete answer in order to get full credit please. Do not copy-paste from diferent site. Thank you
1)Two powerful List functions provided by F# are List.fold and List.foldBack. These are similar to List.reduce and List.reduceBack, but more general. Both take a binary function f, an initial value i, and a list [x1;x2;x3;...;xn]. Then List.fold returns
(f ... (f (f (f i x1) x2) x3) ... xn)
while List.foldBack returns
(f x1 (f x2 (f x3 ... (f xn i) ... )))
In spite of this complicated behavior, they can be implemented very simply:
> let rec fold f a = function | [] -> a | x::xs -> fold f (f a x) xs;; val fold : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a > let rec foldBack f xs a = match xs with | [] -> a | y::ys -> f y (foldBack f ys a);; val foldBack : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b (Note that they don't take their arguments in the same order.)
Each of these functions can be used to implement flatten, which "flattens" a list of lists:
let flatten1 xs = List.fold (@) [] xs let flatten2 xs = List.foldBack (@) xs []
For example,
> flatten1 [[1;2];[];[3];[4;5;6]];; val it : int list = [1; 2; 3; 4; 5; 6]
Compare the efficiency of flatten1 xs and flatten2 xs, both in terms of asymptotic time compexity andexperimentally. To make the analysis simpler, assume that xs is a list of the form [[1];[2];[3];...;[n]].
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
