How to extract the value out of Monads in the Crocks javascript library

427 views Asked by At

I understand that monads typically don't want to unwrap the underlying value because it may or may not exist. In my use case I would like to use functional programming techniques, using ramda for a functional library and Crocks for an algebraic data structure library to write code in a not fully functional codebase. I'm typically going to be using Either, IO, and Maybe monads to write my code, but then extract the final result out of the resultant monad so I can return the value to a function that is not made to accept monads yet.

Folktale has something called getOrElse which will return a value or an undefined/error string. This is super useful and allows me to write functionally in an environment that does not expect to handle monads. Does Crocks have something similar or is there another way to unwrap an Either, IO, or Maybe?

Folktale example that I'd like to replicate in Crocks:

const simpleFunction = (a) => {
    myMaybe = Maybe.of(a);

    // some random transformations on myMaybe

    // this will fall back to the second case if the maybe is empty
    return myMaybe.getOrElse() || doSomethingElseOnError();
}
1

There are 1 answers

0
Dale Francis On BEST ANSWER

Check out the example here, https://crocks.dev/docs/crocks/Result.html#either or https://crocks.dev/docs/crocks/Maybe.html#either I think it's the closest to what you're trying to do.

What you're essentially touching on is folding out the value. In this scenario you need to ensure that you can take a Maybe a and pass in two functions that are () -> b and a -> b where b is the return value of your function that does not want to return a Monad