Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jeremyabbott
Created November 5, 2016 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremyabbott/237ce44fb18542d96ae598c085b8c745 to your computer and use it in GitHub Desktop.
Save jeremyabbott/237ce44fb18542d96ae598c085b8c745 to your computer and use it in GitHub Desktop.
type Result<'a> =
| Success of 'a
| Failure of string
let parseInt x =
try
System.Int32.Parse(x) |> Success
with ex -> ex.Message |> Failure
parseInt "hello"
parseInt "11"
let tryF f x =
try f x |> Success
with ex -> ex.Message |> Failure
let parseInt' x = tryF (System.Int32.Parse) x
parseInt' "hello"
parseInt' "11"
let tryF' f =
try f () |> Success
with ex -> ex.Message |> Failure
let parseInt'' x = tryF' <| fun () -> System.Int32.Parse(x)
parseInt'' "hello"
parseInt'' "11"
let divide x y =
if y <> 0 then x/y |> Success
else "You cannot divide by 0" |> Failure
// Manage a lot of functions with success case
// This is hard to manage
let parseIntDivideByZero x =
match parseInt'' x with
| Success x' ->
match divide x' 10 with
| Success r -> divide r 10
| Failure error -> Failure error
| Failure error -> Failure error
parseIntDivideByZero "100"
parseIntDivideByZero "asdf"
//
let bind f x =
match x with
| Success x'-> f x'
| Failure error -> Failure error
let parseIntDivideByZero' x f =
let x' = bind parseInt (Success x)
let r = bind (fun i -> divide i 10) x'
bind (fun i -> divide i 10) r
let parseIntDivideByZero'' x =
bind parseInt (Success x)
|> bind (fun i -> divide i 10)
|> bind (fun i -> divide i 10)
parseIntDivideByZero'' "100"
parseIntDivideByZero'' "asdf"
let (<!>) x f = bind f x
let parseIntDivideByZero''' x =
parseInt x <!> (fun i -> divide i 10) <!> (fun i -> divide i 10)
parseIntDivideByZero''' "100"
parseIntDivideByZero''' "asdf"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment