Search code examples
functional-programmingmonadsfluent-interface

Do monads have fluent interfaces?


Forgive me if this question seems stupid, but I'm quite new to the whole world of functional programming so I'll need some denizens on StackOverflow to set me straight.

From what I gather, an operation on a monad returns a monad. Does this mean that monads have a fluent interface, whereby each function that is applied on a monad returns that monad after it applies some operation to the variable it wraps?


Solution

  • Presumably you're referring to the bind operator associated with monads, wherein one can start with a monadic value, bind it to a monadic function, and wind up with another monadic value. That's a lot like a "fluent method" (or a set of such making up a "fluent interface") that returns a "this" pointer or reference, yes, but what you'd be missing out on there is that the monadic function need not return a monadic value that's the same type as the input value. The fluent method convention is to return the same type of value so as to continue chaining calls that are all valid on the instance (or instances) being prepared.

    The monadic bind operator signature looks more like this:

    M[a] -> (a -> M[b]) -> M[b]
    

    That is, the "return value" is possibly of a type different from to the first input value's type. It's only the same when the provided function has the type

    (a -> M[a])
    

    It all depends on the type of the monadic function—and, more specifically, the return type of the monadic function.

    If you were to constrain the domain of the monadic functions you'd accept to those that return the same type as the monadic value supplied to the bind operator, then yes, you'd have something that behaves like a fluent interface.