

An Intuitive Use-Case for Monadic Bind and Kleisli Composition - danieljh
https://daniel-j-h.github.io/post/intuitive-monadic-bind-kleisli-composition/

======
dons
> First let us switch to Haskell for pseudocode as I don’t want to show you
> the C++ that is required for this.

Hehe, but that's actual code.

> we may go back to our C++14 code base and implement the ideas there. I’m not
> going to show you how this can be done here, as it requires some more
> boilerplate code to make the compiler happy – as usual.

People are going to want to see the code, otherwise, what's the point?

~~~
danieljh
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...](https://hackage.haskell.org/package/base-4.6.0.1/docs/src/Control-
Monad.html#%3E%3D%3E)

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 :)

~~~
rollo
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.

~~~
coolsunglasses
Haskell wasn't originally designed with Monad in mind either - that came later
and syntax was designed once it was proven out.

