jwood803
10/27/2015 - 10:14 AM

my current favourite handy fsharp helpers

my current favourite handy fsharp helpers

//invaluable for all those Choice<'a, exn> flows
let exnf f = Printf.ksprintf (fun s -> exn s) f

//combine paths
let (</>) x y = System.IO.Path.Combine(x, y)

//allows you to pattern match on values in the current scope rather than just literals
let (|Eq|_|) expected value =
    if expected = value then Some ()
    else None
//Eq example
let hasKV (m : Map<string, string>) k v =
    match Map.tryFind k m with
    | Some (Eq v) -> true
    | _ -> false

//erlang style pattern matching on maps. This one changes everything. :)
let (|Val|_|) = Map.tryFind
//example
let makeForwarder =
    function
    | Val "type" "db" & Val "connection" conn ->
        dbForwarder conn 
    | Val "type" "console" & Val "prefix" prefix ->
        consoleForwarder prefix
    | _ -> errorForwarder

//TryParse functions are much better used through Active Patterns
let (|AsInt64|_|) s =
    match Int64.TryParse s with
    | true, v -> Some v
    | _ -> None
//example
match "1234" with
| AsInt64 x -> "ok"
| _ -> "not ok"