Find the maximum, minimum and average value in F #

I want to find the maximum, minimum and average value in an array without .NET in F #. I used this code, but it does not work:

let mutable max = 0
let arrX = [|9; 11; 3; 4; 5; 6; 7; 8|]

for i in 0 .. arrX.Length - 2 do
  if (arrX.[i]) < (arrX.[i+1]) then 
       max <- arrX.[i]
       printfn "%i" max
+5
source share
4 answers

I fixed your code for max

let mutable max = 0
let arrX= [|9; 11; 3; 4; 5; 6; 7; 8|]

for i in 0 .. arrX.Length - 1 do
  if max < (arrX.[i]) then 
       max <- arrX.[i]
       printfn "%i" max

To find max, min and avg, use your approach:

let mutable max = System.Int32.MinValue
let mutable min = System.Int32.MaxValue
let mutable sum = 0
let arrX= [|9; 11; 3; 4; 5; 6; 7; 8|]

for i in 0 .. arrX.Length - 1 do
  if max < (arrX.[i]) then 
       max <- arrX.[i]
       printfn "max %i" max
  if min > (arrX.[i]) then 
       min <- arrX.[i]
       printfn "min %i" min
  sum <- sum + arrX.[i]
printfn "-> max is %i" max
printfn "-> min is %i" min
printfn "-> avg is %f" (float sum / float arrX.Length)

But note that you can only do:

let max = Seq.max arrX
let min = Seq.min arrX
let avg = Seq.averageBy float arrX
+1
source

While already posted answers are great for why your published code is not working, I would say that using a loop and a mutable variable is not very ... functional. Therefore, I thought that I would post more F # - an idiomatic way to solve it.

, " .NET". , , - .NET. , , , F #.

fold, , . Seq.fold, , :

let rec fold accFn arr acc = 
    match arr with
    | [||] -> acc
    | _ -> fold accFn arr.[1..] (accFn arr.[0] acc)

, accFn , . , .

, , fold:

let min x y =
    if x < y then x 
    else y

let max x y = 
    if x > y then x
    else y

let sum x y = 
    x + y

, :

let arrX= [|9; 11; 3; 4; 5; 6; 7; 8|]
let head = arrX.[0]
let avg = (fold sum arrX 0) / arrX.Length
let minValue = fold min arrX head
let maxValue = fold max arrX head
+7

max . printfn , . :

let mutable max = 0
let arrX= [|9; 11; 3; 4; 5; 6; 7; 8|]

for i in 0 .. arrX.Length-1 do
    if max < arrX.[i] then 
        max <- arrX.[i]
printfn "%i" max
0
let ofArray f (a : 'T array) =
  let len = a.Length
  let rec aux index ret =
    if index >= len then
      ret
    else
      aux (index+1) (f a.[index] ret)
  aux 1 a.[0]

let maxOfArray (a : 'T array) = ofArray max a
let minOfArray (a : 'T array) = ofArray min a
let inline sumOfArray (a : 'T array) = ofArray (+) a

let main() =
  printfn "max: %d" <| maxOfArray arrX
  printfn "min: %d" <| minOfArray arrX
  printfn "ave: %f" <| (sumOfArray arrX |> float) / (arrX.Length |> float)

do main() 
0
source

All Articles