archives

Monads in various languages

While working on implementing monads and comprehensions, I ran into a complication in translating comprehensions to their underlying monadic expressions. Looking at other languages for insight, I realized that all languages which make use of monads use type deduction and that this feature appears to be critical to making comprehensions work.

To translate a comprehension for a monad M, you need to translate expressions like [x+1 | x <- xm] where you know that xm:M(int) for a statically unknown monad M. But how do you typecheck "x+1", which requires that x is a numeric type? Nothing in this expression explicitly indicates that x is numeric. Thus one would need type deduction and explicit universal quantification with matching to deduce that x is numeric, or ugly explicit type specification on comprehensions like [x+1 | x::int <- xm].

My conjecture is that this is why monads happen to be widely-used only in languages supporting Hindley-Milner type deduction, while traditional languages use imperative constructs like iterators, exceptions and side-effects for roughly similar tasks. Monads would be awfully inconvenient without this syntactic sugar, which happens to rely on a rather narrowly-available language feature.

I would appreciate any counterarguments on this conjecture. Also any references to non Hindley-Milner languages supporting monads conveniently.