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

Thinking about the monad, the idea of ​​the monad came to my mind as a way to break von Neumann's architecture. The Von Neumann architecture uses a set of instructions (called programs) to modify data in memory, and executing each program instruction updates the program counter to find out which command is next to execute.

If we think of von Neumann architecture as a monad, the bind (β†’ =) operator will update the program counter. We can make a Monad that breaks von Neumann architecture to do more in binding. As an example, we can have Monad, which counts the number of instructions executed in our programs.

But when I tried to implement this Monad in haskell as:

data Counter a = Counter Integer a deriving( Show ) instance Monad Counter where (Counter n1 a) >>= f = let Counter _ b = fa in (Counter (n1+1) b) return a = Counter 1 a 

I notice that this violates the laws of the Monad, for example:

 return x >>= f /= fx do a <- return 3 return a do return 3 

The two blocks are the same because the laws of the monad, but they will return something else, because they have a different number of instructions (sentences)

Did I do something wrong? or Impossible to have such a Monad?

+7
source share
2 answers

Strictly speaking, any such "monad" violates the laws of the monad and, therefore, ... is not a monad. See this for more information. In other words, your guess is correct, it is impossible to have such a monad.

+8
source

Your implementation throws the number of steps in f. Don't you add them?

  (Counter n1 a) >>= f = let Counter n2 b = fa in (Counter (n1+n2) b) 
+1
source

All Articles