Open research problems/The I/O quandary

From HaskellWiki
< Open research problems
Revision as of 06:18, 31 March 2022 by Atravers (talk | contribs) (Extra reference added)
Jump to navigation Jump to search

[...] we need to come up with better answers about how to interact with the world. The blanket answer of “just push the IO monad through the entire codebase” is not great for a number of reasons [...]

Using unsafePerformIO safely, Victor Miraldo.


Haskell uses the seriously complex machinery of monads to do I/O, supposedly without side effects (I don't accept this). And you end up writing stuff [...] which to me looks like C. There must be a more functional approach.

Monads Schmonads: Functional Input without tears (PyFL), Bill Wadge.


This is hard stuff. Two years ago I spent several hours to write 3 lines invoking IO computations.

Trying to understand the IO (), "belka".


IO is indeed a monad instance, but not a very nice one - the compiler treats it specially, and it is not very nice to reason about [...]

Understanding Monads, Nick Hu.


Haskell compromises brilliantly, by fencing off pure and impure functions from one another [...] The illusion is so good that programmers are fooled into thinking I/O is pure in Haskell. And now that we can write mostly pure code with occasional impure wrappers, researchers have mostly stopped seeking superior alternatives.

A Problem With I/O, Ben Lynn.


Once you’re in the IO monad, you’re stuck there forever, and are reduced to Algol-style imperative programming. You cannot easily convert between functional and monadic style without a radical restructuring of code.

Of Course ML Has Monads!, Robert Harper.


Functional programmers used to worry about how to solve “the I/O problem”. Functional programming (FP) eschews any notion of side-effect or order of execution, and instead has an order-independent notion of evaluation. In contrast, input & output (I/O) seems to be an inherently effectful, ordered notion.

[...]

In a sense, I see us as in a worse position than before. Since the adoption of monadic IO, it’s been less immediately apparent that we’re still enslaved [...] Our current home is not painful enough to goad us onward, as were continuation-based I/O and stream-based I/O. (See A History of Haskell, section 7.1.) Nor does it fully liberate us.

Can functional programming be liberated from the von Neumann paradigm?, Conal Elliott.


Sadly [...] many Haskell programmers believe that IO is necessary to do "real programming", and they use Haskell as if it were C (relegating lots of work to IO). In other words, monadic IO has proved to be such a comfortable "solution" to I/O in a functional language, that very few folks are still searching for a genuinely (not merely technically) functional solution. Before monadic IO, there was a lot of vibrant and imaginative work on functional I/O. [...]

The C language is purely functional, Conal Elliott.


Stream transformers are fragile to use, continuations are powerful but somewhat clutter the syntax of functions. Monads and uniqueness types both present a trade-off, do we accept the over-sequentialisation imposed by monads, or the visual disorder of explicit environment passing? We believe that a compromise is still to be found [...]

Approaches to Functional I/O, Owen Stephens.


The common method to relieve the programming language designer from the inherent IO-problems is to shift responsibility to the programmer who has to sequentialize all IO-requests. This is also true for the monadic approach implemented in Haskell.

FUNDIO: A Lambda-Calculus With letrec, case, Constructors, and an IO-Interface:, Manfred Schmidt-Schauß.


The programming style in a lazy functional language is heavily influenced by the supported I/O-mechanism. Modifying the I/O-behaviour or debugging some lazy functional program that uses I/O is a black art. It is interesting that novices in lazy functional programming in general expect that there is some direct (side-effecting) I/O using a function call.

A Partial Rehabilitation of Side-Effecting I/O:, Manfred Schmidt-Schauß.


The downside of I/O using monads is the need for a monad that can not be unwrapped. So, when using monadic I/O there is no way to get rid of the I/O monad. Furthermore, it is not as intuitive as one would like it to be. A prerequisite to good software design is a thorough understanding of the structures and glues of the implementation language. [...] Yet the understanding of monads is not trivial. The extensive amount of tutorials and questions on the Internet strengthen this thought.

Input/Output in Functional Languages (Using Algebraic Union Types), R.J. Rorije.


The notation for interactive programs written in the monadic style is irritatingly close to the notation used in imperative languages.
[...]
Uniqueness typing addresses the more general problem of statically controlled use of resources in functional programs and, even if combined with passing unique representations of environment objects as arguments to these programs, it does not suffice to solve the input/output-problem. [...] The reason is that the environment is not updated in one conceptual step after the evaluation of a program [...] but rather in small steps whenever the environment representation is modified during program evaluation. The primitive interactions are thus implemented as side-effecting operations, the use of which is rendered safe in the uniqueness-typed environment passing framework.
[...]
Similarly, monads are used to address the more general problem of computations (involving state, input/output, backtracking, ...) returning values: they do not solve any input/output-problems directly but rather provide an elegant and flexible abstraction of many solutions to related problems. [...] For instance, no less than three different input/output-schemes are used to solve these basic problems in Imperative functional programming, the paper which originally proposed `a new model, based on monads, for performing input/output in a non-strict, purely functional language'.
[...]
So, both input/output-schemes merely provide frameworks in which side-effecting operations can safely be used with a guaranteed order of execution and without affecting the properties of the purely functional parts of the language.

Functions, Frames and Interactions, Claus Reinke.


While it is fine that monadic I/O has good theoretical under-pinnings, did anyone stop to think if it helped in user interface programming? If all that it is is a means somehow to construct interactive programs, then it succeeds, but that is not enough. A programmer chooses a language based not on only on ability, but also usability.

Interacting with Functional Languages, Duncan Sinclair.


Although we all love the beautiful aspects of functional languages we must admit that it is difficult to deal with a beast called Input-Output (I/O).

The Beauty and the Beast, Peter Achten and Rinus Plasmeijer.


The I/O problem is mathematical in origin

The various fields of study collectively referred to as mathematics are abstract in one or more ways:

In a preliminary sense, mathematics is abstract because it is studied using highly general and formal resources.

The Applicability of Mathematics, from the Encyclopedia of Philosophy.

In particular, they abstract away from the presence of an outside environment. For programming languages based on one or more of these individual fields of study e.g:

  • Haskell, Clean, Miranda(R): higher-order functions,
  • Prolog: first-order predicate logic,
  • Mercury: both;

this raises the question of I/O and its observable effects:

How must interactions between a program and an external environment (consisting of, e.g., input/output-devices, file systems, ...) be described in a programming language that abstracts from the existence of an outside world?

Functions, Frames and Interactions, Claus Reinke (page 10 of 210).

Input/output is awkward in declarative languages. Some functional languages like LISP have procedural read and write operations. Prolog has ugly read and write "predicates" that execute in sequence. Haskell monads provide pure functional I/O but still involve a sequence of actions.

Specifying Input/Output by Enumeration, Walter W. Wilson and Yu Lei.

It should then be of little surprise that attempts to find a "mathematical solution" for I/O have been less than successful:

Researchers began to analyze why it is often harder to prove things about programs written in traditional languages than it is to prove theorems about mathematics. Two aspects of traditional languages emerged as sources of trouble because they are very difficult to model in a mathematical system: mutability and sequencing.

The Anatomy of Programming Languages, Alice E. Fischer and Frances S. Grodzinsky (emphasis added).

  • What would be ideal is an extension of one or more fields of mathematics which can elegantly describe interactions with external environments - the appropriate denotational semantics can then be used to map it into languages like Haskell or Prolog.
  • Alternately (and less ideally), if it can be proven that one cannot exist (like the solution to the halting problem) then implementors everywhere can just select the most-suitable model of I/O, as they see fit.

An axiomatic approach

The dependently-typed language Agda relies on Haskell for its outside interactions:

4 Compiling Agda programs

This section deals with the topic of getting Agda programs to interact with the real world. Type checking Agda programs requires evaluating arbitrary terms, ans as long as all terms are pure and normalizing this is not a problem, but what happens when we introduce side effects? Clearly, we don't want side effects to happen at compile time. Another question is what primitives the language should provide for constructing side effecing programs. In Agda, these problems are solved by allowing arbitrary Haskell functions to be imported as axioms. At compile time, these imported functions have no reduction behaviour, only at run time is the Haskell function executed.

Dependently Typed Programming in Agda, Ulf Norell and James Chapman (emphasis added).

One possible way to replicate this approach in Haskell is by using its FFI:

instance Monad IO where
    return = unitIO
    (>>=)  = bindIO
    
foreign import ccall "primUnitIO" unitIO :: a -> IO a
foreign import ccall "primBindIO" bindIO :: IO a -> (a -> IO b) -> IO b
                

However, Haskell 2010 doesn't allow higher-order FFI declarations, or their use of type variables. It is possible to devise simpler interfaces which can then be used to implement monadic I/O, but Haskell 2010 also imposes restrictions on its I/O type:

The IO type serves as a tag for operations (actions) that interact with the outside world. The IO type is abstract: no constructors are visible to the user.

The Haskell 2010 Report (page 95 of 329).

On being denotative

Another possibility which has been put forward by some is for languages like Haskell to not just be declarative, but denotative:

My vision of “solving the I/O problem” for functional programming is nothing like Haskell’s semantically imperative (non-)solution (called IO in Haskell), but rather to continue shifting semantically imperative mechanisms out of the programming model and into the implementation of (semantically simple) function application.

Conal Elliott.

because of how various other effects have been moved out of previous languages:

The imperative interfaces in today OSs and data-bases are troubling at first, and indeed I often hear people (even on #haskell) using these examples as demonstration that the imperative programming model is inescapable. These examples don’t trouble me, however, because I see that we’ve already dealt with others of their kind. Underneath the implementation of our current functional abstractions (numbers, strings, trees, functions, etc), there are imperative mechanisms, such as memory allocation & deallocation, stack frame modification, and thunk overwriting (to implement laziness). Every one of these mechanisms can be used as evidence against the functional paradigm by someone who hasn’t yet realized how the mechanism can be shifted out of the role of a programming model notion and into the role of implementation of a programming model notion. The new notion is more composable by virtue of being semantically simpler and mathematically more well-behaved.

Stack and register munging and jump/GOTO are implementations of the semantically simpler notion of function application. (I mean “function” in the sense of math and of pure functional programming.) Moreover, stack & register munging is the input/output (IO) part of the implementation of function application. Information goes out of one context and into another.

Apart from diagnostic purposes, there is now almost no interest in observing these effects, so their relocation into implementations everywhere is entirely reasonable. This is in stark contrast to the simplest of I/O effects, which everyone is interested in observing - that is their raison d’être!

Furthermore, it isn't clear as to how "[...] shifting semantically imperative mechanisms out of the programming model and into the implementation of (semantically simple) function application" would work for those simple I/O effects. For example, consider the sending of '\a' to the standard output device: if it was associated with the application of functions in a language, it would neither be denotative or pleasant (since the language provides no way to control the effect).

Then there's the need to reuse foreign code: an FFI potentially allows countless more effect-centric operations to be accessed. Moving all of them into a finite implementation isn't just impractical - it's impossible.

So there are limits to the ongoing confinement of effects inside implementations, and thus the ability of a language to be both denotative and practical. To truly be considered general-purpose, a programming language must be capable of observable interactions.

Note: none of this constitutes a "proof of impossibility", as eluded to earlier. For example, changing away from the solid-state Turing machines currently in widespread use may render this particular argument academic: only time will tell.

Using more than one language

One suggestion is to ease the relocation of effects into the implementation by using a suitable imperative language:

My view is that the next logical step for programming is to split into two non-overlapping programming domains:

  • runtime building for …
  • … mathematical programming languages

Gabriella Gonzalez.

So instead of having the denotative/imperative division in Haskell by way of types, it would be at the language level in the forms of differing syntax and semantics, foreign calls, and so forth. This too could be alleviated by keeping both languages as similar as possible, but if this is taken to its logical conclusion then the only difference between the denotative and implementation languages would be just the imperative features, which would make having two such similar languages effectively redundant.

Open questions

  • Is there an alternate standalone model of I/O with less problems than each of the current models?
  • If not, can I/O be moved away from the language (as a model) and into the implementation (thus making the language denotative), while keeping the resulting language relatively practical to use?

Other questions

  • Is the C language "purely functional"?
No:
  • C isn't "pure" - it allows unrestricted access to observable effects, including those of I/O.
  • C isn't "functional" - it was never intended to be referentially transparent, which severely restricts the ability to use equational reasoning.
  • Is the Haskell language "purely functional"?
Haskell is not a purely functional language, but is often described as being referentially transparent.
  • Can functional programming be liberated from the von Neumann paradigm?
Only if no-one proves it to be impossible (e.g. like trying to solve the halting problem).
  • Why do our programs need to read input and write output?
Because programs are usually written for practical purposes, such as implementing domain-specific little languages like Dhall.

Other articles