I am new to F#. Is the following code, which represents about three hours of work, a canonical way to achieve its goals. If not, how can it be improved?
For instance, can we provide a default value of zero for the
index parameter? Also, how do we handle a search for a term that does not exist? Could we use something similar to
tail::head instead of matching against
array.[index]? It looks more verbose that it needs to be.
open System let rec linearSearch (array: string) (target: string) (index: int) = match array.Length with | l when index >= l -> -1 | _ -> match array.[index] with | x when x = target -> index | y -> linearSearch array target (index + 1) [<EntryPoint>] let main argv = let names = [| "erdnase" "vernon" "le paul" "scarne" "ireland" |] linearSearch names "le paul" 0 |> printfn "The target is at index: %A" linearSearch names "luttin" 0 |> printfn "The target is at index: %A" 0
The goals for writing the code were:
- Use an array instead of a list, because I would like to understand F# arrays.
- Implement a linear search, because it is a simple algorithm.
- Write in canonical F#, because canonical code is more maintainable.