Skip to content

Instantly share code, notes, and snippets.

@kjnilsson
Last active April 6, 2018 17:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kjnilsson/a56040cdd32fd686ffd1 to your computer and use it in GitHub Desktop.
Save kjnilsson/a56040cdd32fd686ffd1 to your computer and use it in GitHub Desktop.
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 (|Item|_|) = Map.tryFind
//example
let makeForwarder =
function
| Item "type" "db" & Item "connection" conn ->
dbForwarder conn
| Item "type" "console" & Item "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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment