I want to find maximum, minimum and average in an array without .NET in F#. I used this code but it is not working:
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
While the answers already posted are perfectly valid as to why your posted code doesn't work, I would argue that using a loop and a mutable variable isn't very ... functional. So I thought I would post a more F# - idiomatic way of solving it.
You state you "can't use .NET". I am guessing you mean you can't use any of the built-in functions or .NET libraries. Of course, that also means that you can implement them yourself using F# primitives.
One common function in the functional world is
fold
, which simply applies a function to all elements of a sequence, while keeping the return of that function in an accumulator. The built-in version isSeq.fold
, but since we can't use that, we'll define one ourselves:This is a recursive function which applies the
accFn
function to each element, and then calling itself with the remainder of the array. When it gets passed an empty array, recursion terminates.When we have that, let's define some simple functions to pass into
fold
:Once we have that, the solution to the stated problem is simple:
I fixed your code for max
To find max, min and avg, using your approach:
But note you can do just:
There are some logical problem to calculate max here. And the placement of
printfn
will print max each time it changes. The following code works: