Thinking about monad, it came to me the idea of a monad as the way to break with the Von Neumann architecture. The Von Neumann architecture uses a set of instructions (called program) to change the data in memory and the execution of each instruction of the program updates a program counter to know whom instruction is the next to execute.
If we think about the Von Neumann architecture as a monad, the bind operator (>>=) update the program counter. We can make a Monad that break Von Neumann architecture to do more in the bind. As an example, we can have a Monad that count the number of instructions executed in our programs.
But, when I tried to implement that Monad in haskell as:
data Counter a = Counter Integer a
deriving( Show )
instance Monad Counter where
(Counter n1 a) >>= f = let Counter _ b = f a
in (Counter (n1+1) b)
return a = Counter 1 a
I notice it'll break de Monads laws, e.g:
return x >>= f /= f x
do
a <- return 3
return a
do
return 3
The two blocks are the same because the monad laws, but they'll return something different because they have different number of instructions (sentences)
Do I made something wrong? or Is it not possible to have such Monad?
Monads are simply a way to wrapping things and provide methods to do operations on the wrapped stuff without unwrapping it. For example, you can create a type to wrap another one, in Haskell: data Wrapped a = Wrap a. To wrap stuff we define return :: a -> Wrapped a return x = Wrap x.
What is a Monad? A monad is an algebraic structure in category theory, and in Haskell it is used to describe computations as sequences of steps, and to handle side effects such as state and IO. Monads are abstract, and they have many useful concrete instances. Monads provide a way to structure a program.
bind and return are analogous to the corresponding functions of the same name. In fact, int * string , bind , and return form a monad.
Monads are not about ordering/sequencing But this is misleading. Just as you can use monads for state, or strictness, you can use them to order computations. But there are also commutative monads, like Reader, that don't order anything. So ordering is not in any way essential to what a monad is.
Strictly speaking, any such "monad" breaks the monad laws and is thus... not a monad. See this previous question for details. In other words - your guess is correct, it is not possible to have such a monad.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With