I come from a C#/JavaScript/TypeScript background and am learning F# by implementing fundamental algorithms. This is finding the minimum value in an array:
let findMinimumValueIndex (array: int[]): int =
let rec find (index: int) (minimumValueIndex: int) =
let findNext = find (index + 1)
match index with
| i when i >= array.Length -> minimumValueIndex // base case
| i when array.[i] < array.[minimumValueIndex] -> findNext i
| _ -> findNext minimumValueIndex
find 0 0
It works. I like the partial application of arguments in the findNext
function. I like the nested rec
function.
Questions
- How can we make this code more readable?
- How can we make this code a better match of canonical F# style?
- Should we be using
if... then... else
instead ofmatch when
? - Should we be using more explanatory variables?
Test
[<Fact>]
let ``findMinimum returns the index of the minimum value in an array`` () =
let array = [|4; 5; 6; 7; 3; 2; 7; 4; 6; 8; 3|]
let result = findMinimumValueIndex array
Assert.StrictEqual(result, 5);