Consider this pseudo/Haskell code. Functions might fail, so we have to check the return value using nested switches:
modify s f = do
ev <- get s
case ev of
Left e -> return (Left e)
Right v -> do
let u = f v
ev <- set s u
case ev of
Left e -> return (Left e)
Right __-> return (Right (v,u))
Lots of nested checks -- makes the code more unreadable, and harder to maintain. Equivalent to null checks in other languages.The 'case' stuff however, is the monadic 'semicolon' between each statement. So we can refactor to:
modify s f = do
get s
>>= \v -> do
let u = f v
set s u
>>= \v -> do
return (v,u)
Using the error monad definition of bind / >>= - http://hackage.haskell.org/packages/archive/category-extras/...So then, if you language supports monadic syntax, you can actually use semicolon instead of 'bind':
modify s f = do {
v <- get s ;
let u = f v ;
v <- set s u ;
return (v,u) ;
}
and if you are in a whitespace-sensitive language, the error checking disappears into the newline: modify s f = do
v <- get s
let u = f v
v <- set s u
return (v,u)
So the above code, in the Either monad, is equivalent to the original code, however, we now have shorter, cleaner code, and a compile-time guarantee that all return values are checked.This example is my "programmable semicolon" motivator, from http://donsbot.files.wordpress.com/2009/01/semicolon.pdf
I chose the computational environment I wanted my code to run in -- one with checked errors -- and did this by overriding my language's default 'semicolon' behavior using the monad interface to do so.
I reprogrammed my programming language, to make it possible to write better code. That's real power.