Can monads do what this OOP can't?
Question: Trying to understand monads and wondering if they'd be useful for data
transformation programming in Python, I looked at many introductory
explanations. But I don't understand why monads are important.

Is the following Python code a good representation of the Maybe monad?

    
    
    class Some:
        def __init__(self, val):
            self.val=val
    
        def apply(self, func):
            return func(self.val)
    
    
    class Error:
        def apply(self, func):
            return Error()
    
    
    a = Some(1)
    b = a.apply(lambda x:Some(x+5))
    

Can you give an example of a monad solution, which cannot be transformed into
such OOP code?

(Do you think monads for data transformation in OOP languages can be useful?)


Answer: Here is a post that discusses monads using Swift as the language that might
help you make more sense of them: <http://www.javiersoto.me/post/106875422394>

The basic point is that a monad is an object that has three components.

  1. A constructor that can take some other object, or objects, and create a monad wrapping that object.
  2. A method that can apply a function _that knows nothing about the monad_ to its contents and return the result wrapped in a monad.
  3. A method that can apply a function that takes the raw object and returns a result wrapped in the monad, and return that monad.

Note that this means even an Array class can be a monad if the language treats
methods as first class objects, and the necessary methods exist.

If the language doesn't treat methods as first class objects, _even if it's an
OO language_ , it will not able able to implement Monads. I think your
confusion may be coming from the fact that you are using a multi-paradigm
language (Python) and assuming it is a pure OO language.

