Two common examples from the Ocaml world are promises through the LWT library and options.
If you just wanted to open a file, maybe you would write something like this:
run(create_file("filename"))
Here `create_file("filename")` is a pure value, no side effects. It's a value that represents the concept of creating `"filename"` (and maybe returning a handle). When passed to `run`, that value is inspected and only then the actual action it corresponds to, creating a file, is executed.What if you want to do something with the file? That looks like this:
let create_then_delete = and_then(open_file("filename"), (handle) -> delete_file(handle))
run(create_then_delete)
`create_then_delete` represents the concept of opening a file and giving it to `(handle) -> delete_file(handle)`. If you want to actually do that, you pass `create_then_delete` to `run`.Functions with a type signature similar to `and_then` turn out to be pretty common, so it's nice to have a way to talk about them. That's basically what monads are for. In OCaml, all functions that have a similar type signature can use the new "let-monadic syntax", which basically lets you rewrite
and_then(open_file("filename"), (handle) -> delete_file(handle))
to let\* handle = open_file("filename");
delete_file(handle)
Which is a lot more readable if you ask me. Any type that has a function like `and_then` works with this syntax, and those types called monads.