Lightweight monadic programming in ML

Nikhil Swamy, Nataliya Guts, Daan Leijen, Michael Hicks
2011 Proceeding of the 16th ACM SIGPLAN international conference on Functional programming - ICFP '11  
Many useful programming constructions can be expressed as monads. Examples include probabilistic modeling, functional reactive programming, parsing, and information flow tracking, not to mention effectful functionality like state and I/O. In this paper, we present a type-based rewriting algorithm to make programming with arbitrary monads as easy as using ML's built-in support for state and I/O. Developers write programs using monadic values of type m τ as if they were of type τ , and our
more » ... hm inserts the necessary binds, units, and monad-to-monad morphisms so that the program type checks. Our algorithm, based on Jones' qualified types, produces principal types. But principal types are sometimes problematic: the program's semantics could depend on the choice of instantiation when more than one instantiation is valid. In such situations we are able to simplify the types to remove any ambiguity but without adversely affecting typability; thus we can accept strictly more programs. Moreover, we have proved that this simplification is efficient (linear in the number of constraints) and coherent: while our algorithm induces a particular rewriting, all related rewritings will have the same semantics. We have implemented our approach for a core functional language and applied it successfully to simple examples from the domains listed above, which are used as illustrations throughout the paper. Monad(Beh, bindb, unitb) As a primitive, function seconds has type unit → Beh int, its result representing the current time in seconds since the epoch. An ML program using Beh effectively has two monads: the implicit monad, which applies to normal ML computations, and the userdefined monad Beh. The former is handled primitively but the latter requires the programmer to explicitly use bindb, unitb, function composition, etc., as in the following example: bindb (bindb (seconds()) (fun s-> unitb (is_even s))) (fun y-> unitb (if y then 1 else 2)) The type of this entire expression is Beh int: it is time-varying, oscillating between values 1 and 2 every second. Instead of using tedious explicit syntax, we would like to overload the existing syntax so that monadic constructs are implicit, e.g., as in the following program (call it Q) let y = is_even (seconds()) in if y then 1 else 2 We can see that the programs are structurally related, with a bind corresponding to each let and application, and unit applied to the bound and final expressions. While ML programming with one monad is tedious, programming with more than one is worse. Along with different binds and units for each monad, the programmer may have to insert calls to
doi:10.1145/2034773.2034778 dblp:conf/icfp/SwamyGLH11 fatcat:why65xdo4jggnbr2t3ytx7zvsu