4 ms·
macros are compilers, monads are interpreters
by dustingetz 5y ago
macros are compilers, monads are interpreters
- celeritascelery 5y agoTrying to wrap my head around this. How are monads like interpreters?
- chalst 5y agoIf you look at each as languages for staging computations, what you stage with macros happens before "normal" computation, so likely happens at compile time, while what you stage with monads happens after, so must be deferred to run time.
- dustingetz 5y agogoogle "monadic interpreter" One thing monad/bind can do that macros cannot is make arbitrary runtime decisions about what to do next, with runtime information. A macro is constrained by what is known statically in the AST. This is why compiled languages are far easier to optimize (it is merely algebraic rewrites of the AST) whereas dynamic languages have runtime eval.
- Tyr42 5y agoLets get concrete and make a simple example State monad. You have access to an extra variable S, with getS and setS, and each of those return values of our StateMonad. Using these (and >>= aka bind) you can write something which increments the number in the state by one, yes? increment = do s <- getS setS (s+1) and this increment is a value of our StateMonad. This doesn't run on it's own though, it needs the "interpreter" to run the state monad, and put in a initial value of the state, and maybe take it out at the end. That's the way you can think of Monads as interpreters in a very rough sense. Now, you can do fancier things, where you can set up a "free monad", which is basically going to record everything into a syntax tree, and then you really have an interpreter. http://blog.sigfpe.com/2006/08/you-could-have-invented-monads-and.html http://blog.sigfpe.com/2006/08/you-could-have-invented-monad...