Mutability in functional programming

前端 未结 4 746
猫巷女王i
猫巷女王i 2021-02-05 13:02

First I am a Haskell newbie. I\'ve read this: Immutable functional objects in highly mutable domain And my question is nearly the same -- how to efficiently write algorithms whe

相关标签:
4条回答
  • 2021-02-05 13:15

    Creating new immutable objects isn't nearly as expense as you might think, since large amounts of structural sharing can occur because the compiler KNOWS they can't change and thus can be safely shared. That said, using highly imperative algorithms with lots of mutable state in Haskell is a bit of a code smell.

    0 讨论(0)
  • 2021-02-05 13:24

    In ML derivatives (such as OCaml, SML, F#), there are "references", which can be used as mutable variables.

    In Haskell, this isn't cleanly handled. State is simply not covered by the usual "purely functional" style. Pure FP languages deal with "eternal truths", and are thus not very suitable for working with "ephemeral truths" (although it can be done, definitely).

    However, yes, sometimes we need mutable state. A language such as ATS incorporates linear types for handling destructive updates and safe resource manipulation.

    0 讨论(0)
  • 2021-02-05 13:27

    There are of course many ways functional languages address this issue.

    1. Different data structures - many data structures can be implemented in a purely functional manner, with the same algorithmic complexity as imperative versions. Probably the most well-known work in this area is Chris Okasaki's Purely Functional Data Structures, but there are many other resources as well. For Dijkstra's algorithm, Martin Erwig's work on functional graphs is appropriate. See this question as well.

    2. Different algorithms - some algorithms have assumptions of mutability built-in, Quicksort is an example of this. In this case an alternative algorithm can be used that's more amenable to immutability.

    3. Mutable state - every functional language can model functional state with a State monad. Most provide other forms of mutability as well, such as Haskell's ST monad and IORef's.

    0 讨论(0)
  • 2021-02-05 13:29

    The ST Monad lets you use mutable state internally, but present a pure external interface.

    0 讨论(0)
提交回复
热议问题