Hacker News new | ask | show | jobs
by danieljh 4067 days ago
The reason I did not show code is that there is 1/ no notion of a monad type class in C++ 2/ no std::optional in the current C++14 standard and 3/ you have to work around side effects, making an actual implementation highly dependent on your environment and so on.

I'm playing around with what is now my second iteration of Monadic Bind and Kleisli Composition for boost::optional, which looks something like this right now:

    // tag dispatch work around for void returning functions (that make no sense in a purely functional world)
    namespace detail {
        template <typename A, typename Fn>
        auto monadicBindImpl(const boost::optional<A>& a, Fn f, std::false_type) -> decltype(f(*a)) {
            if (a) return f(*a); else return {};
        }
   
        template <typename A, typename Fn>
        auto monadicBindImpl(const boost::optional<A>& a, Fn f, std::true_type) -> void {
            if (a) f(*a);
        }
     }

    template <typename A>  
    auto pure(A&& a) { return boost::optional<A>(std::forward<A>(a)); }  

    template <typename A, typename Fn>  
    auto operator>>=(const boost::optional<A>& a, Fn f) -> decltype(f(*a)) {
        return detail::monadicBindImpl(a, f, typename std::is_same<decltype(f(*a)), void>{});
    }  
Kleisli Composition can then be build with C++14's generic polymorphic lambdas exactly like the Haskell implementation does it: https://hackage.haskell.org/package/base-4.6.0.1/docs/src/Co...

There are other articles on the web for Monads in C++, that probably do a better job at an actual implementation. Please see this as my personal playground code :)

1 comments

The way the C++ code looks makes me think that the language wasn't designed with this in mind. Modern programming concepts are really stretching the syntax of older languages to the point that there is just too much noise that is distracting from what is actually being done which makes simple things look confusing and complicated. I guess there is a reason Haskell code was used to demonstrate the concept.
Haskell wasn't originally designed with Monad in mind either - that came later and syntax was designed once it was proven out.