Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a Monad that count the number of instructions?

Tags:

haskell

monads

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?

like image 840
Zhen Avatar asked Oct 31 '11 16:10

Zhen


People also ask

What are monads explain with example?

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.

How does a monad work?

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.

Is string a monad?

bind and return are analogous to the corresponding functions of the same name. In fact, int * string , bind , and return form a monad.

What a monad is not?

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.


1 Answers

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.

like image 85
Thomas M. DuBuisson Avatar answered Oct 09 '22 08:10

Thomas M. DuBuisson