Disable exception handling
include Sugar.S.Result_partials
Apply the binding only if the computation was successful. You can use the operator >>= instead of this function for syntatic sugar
Apply the binding only if the computation failed.
Notice that an error handler must be provided, and this handler must throw an error or provide an equivalent for the result type of the previous computation.
You can use the operator >--------- instead of this function for syntatic sugar
Apply a function to the result of a successful computation. This function makes it ease to work with non error aware functions.
Example:
open Sugar.Option
let twenty =
map (Some 10) (fun n -> n + n)
You could also use the combinator >>| for syntatic sugar.
val return : 'a ‑> 'a result
Return a value in a successful computation.
This function should be used with its counterpart, throw
Return an error as the result of a computation.
Like the return
function, throw
helps you hide the internals of your
result type and keep a clean code.
If you are still at the beginning of your project, and don't have your
errors defined yet, this function still is a great help. For example,
the code bellow have the same usage as the function failwith
, but is a lot
safer.
module MyResult = Sugar.MakeResult (struct error = string end)
open MyResult
let run (): int result =
if true then
return 10
else
throw "something bad happend"
You could also not describe your errors at all for some time, and use the Sugar.Option module to create error aware computations, like:
open Sugar.Option
let run (): string result =
if true then
return "hello world"
else
throw ()
module Infix : sig ... end
Bind combinator
If the computation in the left is successful, the operator will
Take the inner value and feed it to the function in the right. This is an
alias for the function bind
.
If the computation in the left failed, the operator will propagate the error, skipping the function completely.
val unwrap : 'a result ‑> 'a
Unwraps the successful result as a normal value in the threading monad. If the value is not successful, it will raise an Invalid_arg exception.
Unwraps the successful result as a value in the threading monad.
Different from unwrap
, you can assign an error handler to be
executed if the computation failed. Example:
let run () =
get_data ()
|> unwrap_or (fun _ -> "default")
val expect : 'a result ‑> string ‑> 'a
Extracts a successful value from an computation, or raises and Invalid_arg exception with the defined parameter.
module For : functor (UserMonad : Sugar.S.Params.Monad) -> Sugar.S.Promise with type error := error and type a monad := a UserMonad.t
Create a new result module based on the current one, but wrapped around a monad.