bs-result
Monadic interface for Belt.Result
This implementation is inspired by JavaScript Fantasy Land and closely follows the Funfix.org Either implementation.
Installation
- Install the
bs-result
package.yarn add bs-result
- Add
bs-result
to yourbsconfig.json
{ "dependencies": [ "bs-result" ] }
Usage
Basic
let r =
Result.return(20)
|> Result.map(x => x + 20)
|> Result.flatMap(x => Result.return(x + 2))
|> Result.getOrElse(-1);
Js.log2("Result: ", r);
[@@@ocaml.ppx.context { cookies = [] }]
let r =
(((Result.return 20) |> (Result.map (fun x -> x + 20))) |>
(Result.flatMap (fun x -> Result.return (x + 2))))
|> (Result.getOrElse (-1))
let _ = Js.log2 (("Result: ")[@reason.raw_literal "Result: "]) r
Integrations
Belt.Result
let r =
Belt.Result.Ok(x => x + 10)
|> Result.ap(Result.return(20))
|> Belt.Result.map(_, x => x + 10)
|> Result.flatMap(x => Belt.Result.Ok(x + 2))
|> Belt.Result.getWithDefault(_, -1);
Js.log2("Result: ", r);
[@@@ocaml.ppx.context { cookies = [] }]
let r =
(((((Belt.Result.Ok ((fun x -> x + 10)))[@explicit_arity ]) |>
(Result.ap (Result.return 20)))
|> (fun __x -> Belt.Result.map __x (fun x -> x + 10)))
|>
(Result.flatMap
(fun x -> ((Belt.Result.Ok ((x + 2)))[@explicit_arity ]))))
|> (fun __x -> Belt.Result.getWithDefault __x (-1))
let _ = Js.log2 (("Result: ")[@reason.raw_literal "Result: "]) r
Js.Promise
Js.Promise.resolve(20)
|> Js.Promise.then_(x => Result.Promise.return(x))
|> Result.Promise.flatMap(x => Result.return(x + 10))
|> Result.Promise.map(x => x + 10)
|> Result.Promise.andThen(x =>
x + 2 |> Result.return |> Js.Promise.resolve
)
|> Result.Promise.unsafeResolve
|> Js.Promise.then_(result => {
Js.log2("Result: ", result);
Js.Promise.resolve();
})
[@@@ocaml.ppx.context { cookies = [] }]
let _ =
((((((Js.Promise.resolve 20) |>
(Js.Promise.then_ (fun x -> Result.Promise.return x)))
|> (Result.Promise.flatMap (fun x -> Result.return (x + 10))))
|> (Result.Promise.map (fun x -> x + 10)))
|>
(Result.Promise.andThen
(fun x -> ((x + 2) |> Result.return) |> Js.Promise.resolve)))
|> Result.Promise.unsafeResolve)
|>
(Js.Promise.then_
(fun result ->
Js.log2 (("Result: ")[@reason.raw_literal "Result: "]) result;
Js.Promise.resolve ()))
Full API Docs
TODO
- [ ] Integration with reason-future.
- [ ] Comonad implementation - functions are mis-named.