How do functional languages model side-effects?

前端 未结 3 1952
花落未央
花落未央 2020-12-13 19:55

Since side-effects break referential transparency, don\'t they go against the point of functional languages?

3条回答
  •  有刺的猬
    2020-12-13 20:32

    There are several options available to handle I/O in a functional language.

    • Don't be pure. Many functional languages aren't purely functional. It's more that they support functional programming rather than enforcing it. This is by far the most common solution to the problem of I/O in functional programming. (Examples: Lisp, Scheme, Standard ML, Erlang, etc.)
    • Stream transformation. Early Haskell I/O was done this way. Check my link below for details if you want more information. (Hint: you probably don't.)
    • Continuation-passing I/O (the "world-passing" mentioned in other answers). In this one you pass a token of data around with your I/O that acts as the necessary "different value" to keep referential integrity alive. This is used by several ML dialects if memory serves.
    • The "continuation" or "world" thing above can be wrapped in various data types, the most (in)famous being the use of monads in this role in Haskell. Note that this is, notionally, the same thing under the covers, but the tedium of keeping track of "world"/"continuation" state variables is removed.

    There's a research dissertation that exhaustively analyses these.

    Functional I/O is an ongoing field of research and there are other languages which address this issue in interesting and mind-mangling ways. Hoare logic is put to use in some research languages. Others (like Mercury) use uniqueness typing. Still others (like Clean) use effect systems. Of these I have a very, very limited exposure to Mercury only, so I can't really comment on details. There's a paper that details Clean's I/O system in depth, however, if you're interested in that direction.

提交回复
热议问题