Question 1
Given the list below, use scan
to return the intermediate and final cumulative sums.
[ 1; -4; 7; 2; -10]
answer(0, [ 1; -4; 7; 2; -10])
||> List.scan (fun acc x -> acc + x)
val it: int list = [0; 1; -3; 4; 6; -4]
Question 2
Given the list below, use fold
to return the final sum.
[ 1; -4; 7; 2; -10]
answer(0, [ 1; -4; 7; 2; -10])
||> List.fold (fun acc x -> acc + x)
val it: int = -4
Question 3
Given the list below, use mapFold
to return the intermediate and final cumulative sums.
[ 1; -4; 7; 2; -10]
answer(0, [ 1; -4; 7; 2; -10])
||> List.mapFold (fun acc x -> acc + x, acc + x)
val it: int list * int = ([1; -3; 4; 6; -4], -4)
Question 4
Given the list below, use mapFold
to return a tuple of
- A new list in which each element of the original list is transformed by adding
1
to it and then converted into astring
. - The final cumulative sums of the list elements.
[ 1; -4; 7; 2; -10]
answer(0, [ 1; -4; 7; 2; -10])
||> List.mapFold (fun acc x -> string (x + 1), acc + x)
val it: string list * int = (["2"; "-3"; "8"; "3"; "-9"], -4)
Question 5
Given the list below, use mapFold
to return a tuple of
- The list of records with the
Y
field in each record updated toY+1
- The sum of the
Y
fields.
type R1 = { X : string; Y : int }
let r1xs =
[ { X = "a"; Y = 1 }
{ X = "b"; Y = -4 }
{ X = "c"; Y = 7 }
{ X = "d"; Y = 2 }
{ X = "e"; Y = -10 }]
answer(0, r1xs)
||> List.mapFold (fun acc x -> { x with Y = x.Y+1}, acc + x.Y)
val it: R1 list * int =
([{ X = "a"
Y = 2 }; { X = "b"
Y = -3 }; { X = "c"
Y = 8 }; { X = "d"
Y = 3 }; { X = "e"
Y = -9 }], -4)
module List from Microsoft.FSharp.Collections
--------------------
type List<'T> = | op_Nil | op_ColonColon of Head: 'T * Tail: 'T list interface IReadOnlyList<'T> interface IReadOnlyCollection<'T> interface IEnumerable interface IEnumerable<'T> member GetReverseIndex: rank: int * offset: int -> int member GetSlice: startIndex: int option * endIndex: int option -> 'T list static member Cons: head: 'T * tail: 'T list -> 'T list member Head: 'T member IsEmpty: bool member Item: index: int -> 'T with get ...
val string: value: 'T -> string
--------------------
type string = System.String
val int: value: 'T -> int (requires member op_Explicit)
--------------------
type int = int32
--------------------
type int<'Measure> = int