Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IO Monad in Dynamically-typed Languages

In Haskell, one of the things which I feel is quite beautiful is its use of Monads as an abstraction over effectful actions. It creates a really elegant way to express imperative code, while also allowing powerful things to happen with guarantees about correctness.

The IO monad doesn't seem to be specific to strongly typed languages. Specifically, it seems to me that it wouldn't be difficult or revolutionary to implement the IO monad in a dynamically typed language. It would then only be necessary to restrict the language such that all IO actions instead simply produce actions in the IO monad.

That being said, I haven't seen any languages (perhaps I am simply not looking hard enough) which are dynamically typed, yet isolate side effects using monads. Is there any reason why this is the case? (or do they exist?)

like image 618
Mystor Avatar asked Jul 10 '14 02:07

Mystor


1 Answers

You have conflated two issues here. I can't blame you for this, because much of the literature on Haskell also conflates the two ideas. But typed IO is where the magic in Haskell's approach comes from. The fact that the IO type forms a monad isn't really that important. It just means it gets to share library functions with other types, instead of reimplementing them itself.

The monad abstraction doesn't really work very well in dynamically-typed languages. Sure, they can give you analogs to fmap and (>>=), but there's no good way for return to work in a dynamically-typed language. It is polymorphic in a type variable that appears only in its return type. I'm not aware of any language with dynamic typing that's equipped to handle that sanely. I suppose there are probably ways to hack it using something like a free monad construction and tons of introspection, but I doubt it would ever seem like a helpful abstraction.

The other portion though, typed IO, could possibly be integrated into a dynamic language. Obviously it would become runtime-tagged IO, rather than typed IO. But everything about the language would have to be built to support it. The entry point for program execution would have to be specified to be an IO value, rather than the common idiom of just executing every line in the file like most dynamic languages choose. Then you would have to compose IO values using either combinators or syntax, as in Haskell. And finally, you'd have to put up with users claiming the language is too hard to use, because it's not identical to what they're used to.

Really, it's the last one that's a killer.

like image 65
Carl Avatar answered Nov 11 '22 06:11

Carl