LoopPerfect / neither

Either and Maybe monads for better error-handling in C++ ↔️
MIT License
249 stars 18 forks source link

Implement MetaFunctions ensureEither #10

Closed nikhedonia closed 7 years ago

nikhedonia commented 7 years ago

To express the type contracts of (left/right) flatMap and map, we should introduce meta functions for SFINAE.

template<class L, class R>
auto ensureEither( Either<L,R> const& e) - > decltype( e ) {
   return e;
}

template<class L, class R>
auto ensureEither( Either<L,R> const& e, L, R ) - > decltype( e ) {
   return e;
}

template<class L, class R>
auto ensureEitherLeft( Either<L,R> const& e, L) - > decltype( e ) {
   return e;
}

template<class L, class R>
auto ensureEitherRight( Either<L,R> const& e, R) - > decltype( e ) {
   return e;
}

This could be used to express the contracts of map:

  template<class LeftCase>
  auto leftFlatMap(LeftCase leftCase) -> decltype(
    ensureEitherRight( leftCase(leftValue), rightValue ) 
  ) {
    if (!*this) {
      return leftCase( leftValue );
    }

    return NextEither::rightOf(rightValue);
}