3

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();
}
kierans
  • 2,034
  • 1
  • 16
  • 43
Justin Hoyt
  • 148
  • 1
  • 9
  • 1
    Monads are systemic. You cannot extract their values in a general manner. If you want to, don't use them. Functions don't need to be aware of monads. Either lift them into the right context or compose them with `of` if you need a third party function to return a monadic value. In some cases you'll need special conversion functions, that's all. –  Oct 07 '20 at 09:04
  • 1
    Like scriptum said, "monads" in general do not have such a method, it's not part of that *interface*, it is not possible to extract values from them. However, all the concrete data structures `Either`, `IO` and `Maybe` do have such methods individually. – Bergi Oct 07 '20 at 23:37
  • 1
    OP is essentially looking for a fold operation on the Maybe and Either types, and some sort of unsafeExecute for IO. – user1713450 Oct 16 '20 at 06:41

1 Answers1

2

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

Dale Francis
  • 537
  • 2
  • 10