Hacker News new | ask | show | jobs
by csense 4916 days ago
Thanks for the lengthy reply!

So Monads are a complicated error-propagation framework that has a harder-to-understand conceptual model and results in longer code compared to Python's exceptions.

Look at any serious program in the C language -- there are enormous amounts of code devoted to error handling.

Look at the problem with Java's checked exceptions. The other day I needed to call a static method reflectively. This is what I ended up with:

  // java code to invoke a named method on a named class
  String the_class_name;
  String the_method_name;

  try
  {
     c = Class.forName(the_class_name);
     result = (Value) c.getDeclaredMethod(the_method_name).invoke(null);
  }
  catch (ClassNotFoundException e)
  {
     throw(new RuntimeException(e));
  }
  catch (IllegalAccessException e)
  {
     throw(new RuntimeException(e));
  }
  catch (IllegalArgumentException e)
  {
     throw(new RuntimeException(e));
  }
  catch (InvocationTargetException e)
  {
     throw(new RuntimeException(e));
  }
  catch (NoSuchMethodException e)
  {
     throw(new RuntimeException(e));
  }
  catch (SecurityException e)
  {
     throw(new RuntimeException(e));
  }
The point that Python's Exception model gets right, that so many other languages get wrong, is that by default, you want to pass errors to the caller.

You don't want to pass errors through the same pipeline that results flow through, since then every joint in the plumbing needs error checking. The very name "exception" is chosen to denote an "extraordinary control flow" specifically for error handling.

2 comments

No, of course not. Error handling is just one example. The monad interface makes handling that problem you mention---wiring errors through the value pipeline---much easier.

And the monad part is only just the "just" and "bind" functions. Everything else is about trying to make Python more explicit with its errors: "explicit it better than implicit", right?

Monads allow for easier composition of "values in context". That context might be error, or nondeterminism, or continuation, or state, or logging, or parsing, or parallelism, or simulation, or probability, or graphs, or prolog-like logic, or streaming, or many combinations over the previous.

And in every case, you have the same interface.

If your only standard for utility is applicability to Python there's no point discussing monads or anything else that comes up in conversations about languages besides Python. Maybe the reason you haven't seen a cogent explanation of monads using only Python is the same as the reason you haven't seen a cogent explanation of how to use the clutch in an automatic car, or how to desalinate fresh water, or how to make lemonade with nothing but a jug and ice water. Maybe the problem isn't the explanation or the one producing it.