A Collection of Code Snippets in as Many Programming Languages as Possible
This project is maintained by TheRenegadeCoder
Welcome to the Insertion Sort in F# page! Here, you'll find the source code for this program as well as a description of how the program works.
open System
module InsertionSort =
let rec private insert sorted x =
match sorted with
| [] -> [ x ] // Insert at end
| head :: tail when x <= head -> x :: sorted // Found spot
| head :: tail -> head :: insert tail x // Keep traversing
let run numbers =
numbers |> List.fold insert [] |> List.map string |> String.concat ", " |> Ok
module Result =
let toOption =
function
| Ok x -> Some x
| Error _ -> None
module Helpers =
let private (|IntList|_|) (s: string) =
let ns =
s.Split(',', StringSplitOptions.RemoveEmptyEntries)
|> Array.toList
|> List.map (fun p ->
match Int32.TryParse(p.Trim()) with
| true, n -> Ok n
| false, _ -> Error $"Invalid integer: '{p}'")
|> List.choose Result.toOption
if ns.Length >= 2 then Some ns else None
let parseArgs argv =
match argv with
| [| IntList numbers |] -> Ok numbers
| _ -> Error "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""
let handleResult =
function
| Ok result ->
printfn "%s" result
0
| Error msg ->
eprintfn "%s" msg
1
[<EntryPoint>]
let main argv =
argv
|> Helpers.parseArgs
|> Result.bind InsertionSort.run
|> Helpers.handleResult
Insertion Sort in F# was written by:
If you see anything you'd like to change or update, please consider contributing.
No 'How to Implement the Solution' section available. Please consider contributing.
No 'How to Run the Solution' section available. Please consider contributing.