I was watching this Computerphile video: "What is a Monad?" What is a Monad? - Computerphile - YouTube thinking that Computerphile were likely to be able to explain what is a monad in a simple enough way for normal people to understand.
The explanation revolves around creating as simple expression evaluator in Haskell, which has to not crash on divide by zero. This is already going down hill, who knows Haskell? But I persevere:
He starts with writing the Haskell data type:
data Expr = Val Int | Div Expr Expr
Well, soon I'm lost in the weeds, as are most other commentators on that video, but that single line at the start suggested a Rust Option or Error type.
Many hours later.... I had this expression evaluator running in Rust:
#[derive(Debug, Clone)]
enum Expr {
Value(Option<i32>),
Div(Box<(Expr, Expr)>),
}
fn safe_div(m: Option<i32>, n: Option<i32>) -> Option<i32> {
match (m, n) {
(Some(m), Some(n)) => {
if n == 0 {
None
} else {
Some(m / n)
}
},
(_,_) => None
}
}
fn eval(e: Expr) -> Option<i32> {
match e {
Expr::Value(v) => v,
Expr::Div(operands) => safe_div(eval(operands.0) , eval(operands.1)),
}
}
Which as far as I can tell does what the Haskell code in the video does. Using Rust's Option type rather than the Haskell's Maybe monad. As far as I can tell it is not much longer and far easier to read!
The presenter says that this "monad" thing is one of the greatest developments in computer science in 25 years. But surely we have been doing this in languages like C since forever, with tagged unions and function pointers? Did the computer science guys just find out how to program? Of course it's a big thing that languages like Haskell and Rust support this kind of thing very robustly rather than hacking it together in C.
Anyway, I still don't know what a monad is. Where is the monad? Apparently there is one in there as rust analyzer popped up occasionally with some message about "rust-monad".
Is there a better way to do what I have there? Before I start extending it for other operators?