spebbe / dartz

Functional programming in Dart
MIT License
749 stars 60 forks source link

Is there a Try? #79

Closed najibghadri closed 3 years ago

najibghadri commented 3 years ago

Hello. Say I have a function () => A that might throw an error. Is there a monad/function that turns it into an Option. Afaik this is called Try. There is IOMonad and Free monad but I can't figure out they serve this purpose.

najibghadri commented 3 years ago

Obviously I can make my own, but still, wondering what is the standard here.

Option<A> tryOf<A>(A Function() f) {
  try {
    return optionOf(f.call());
  } catch (e) {
    return None();
  }
}
ibcoleman commented 3 years ago

@najibghadri The only thing I see like that is Either's catching function... but that's not quite it.

spebbe commented 3 years ago

@najibghadri, the catching function that @ibcoleman mentions is probably the closest thing in dartz at the moment. It returns Either values, capturing any thrown exceptions as Left values, but if you want to discard any captured exception information you can always do

final maybeResult = catching(() => ...).toOption();
najibghadri commented 3 years ago

This is it, lovely, thank you guys! 😊 🙏

najibghadri commented 3 years ago

@ibcoleman And yes, I love the running joke.. There is no Try and that's it.