3 ms·
What's cool about monads is that the computation (assembly code in this particular case) is just a plain old value. So if you have a fragment like this: f
by pka 11y ago
What's cool about monads is that the computation (assembly code in this particular case) is just a plain old value.
So if you have a fragment like this:
factorial :: Int64 -> X86 ()
factorial n = do
mov rcx (I n)
mov rax (I 1)
l1 <- label
mul rcx
loop l1
ret
you can just compose this into a bigger program:
two_factorials :: Int64 -> Int64 -> X86 ()
two_factorials n1 n2 = do
factorial n1
factorial n2
Notice how the labels won't get mixed up. This concept (representing computation by values) is incredibly powerful: one can compose, combine, abstract values into bigger values. For example, compare the compositional properties of RethinkDB's query language to SQL.
- anon4 11y agoCorrect me if I'm wrong, but isn't this basically the same as an HTML DSL, i.e. functions which transform something like (in LISP) (html (head (title "hello")) (body (p "world"))) into "<html><head><title>hello</title></head><body><p>world</p></body></html>"? Except this takes assembly keywords and outputs machine code.
- dmytrish 11y agoYes, there is some similarity in expressive power of Lisp macros and Haskell monads (edit: raw Lisp macros are even more powerful, since they may glue and transform anything to anything). However, there is a huge difference in the essence: Lisp macros work on the syntactic level, monads compose on the semantics level. Lisp macros are not bound by types, so they can be combined irregardless of a program semantics, potentially producing any kind of incorrect code as the result. Such errors get especially tricky with several layers of quasiquotation. In Haskell, the program meaning is partially encoded into types, so the compiler can understand your intention much better and assists you in programming it right. Also, getting some kind of inter-part optimization is much easier in Haskell: you know exactly what kind of pieces you are gluing up.
- dmytrish 11y agoYes, and you even can put your whole-block optimizations between the statements being glued (that's the magic of the custom composition primitives, monads).