Monadic Programming in Imperative Languages - Anderlind, Joakim; Åsberg, Mårten (My University, 2023)
Using monads as a generalised interface for abstracting computations has seen great success in functional languages such as Haskell. By generalising computations as monadic actions, one can use a specialised syntax, such as the do-notation of Haskell, to compose these actions into clearer programs. Although certain monadic features have been introduced into imperative languages, such as the various flatMap methods in Java or the try-operator in Rust, there is a lack of a generalised interface for composing monadic actions. The goal of this thesis is to investigate how monadic abstractions from functional languages can be transferred to imperative languages. To accomplish this, we present an interface for composing monadic actions that can be integrated within existing imperative languages. We begin with defining how our interface should be integrated within a host language while preserving the original semantics of said languages to as large a degree as possible. Then we develop an implementation of our interface in Rust via its procmacro system. Additionally, we developed a C# implementation of our interface for comparison. Finally, we benchmark the Rust implementation to analyse the potential performance cost of our interface. Using our Rust and C# implementations, we were able to integrate monads such as the Option, Writer, State, and List monads with minimal changes to existing syntax. Benchmarks shows that the interface itself introduces a noticeable performance cost compared to reference implementations without our interface. For future work, we suggest working on improvements of the usability and developer experience, that our interface may be implemented in other imperative languages, and that more research is needed into improving the performance of our interface.
Keywords: monads; programming languages; language design; Rust; C#