Functional programming: how far should immutability go?

I understand that this is probably a rather subjective question, but I'm looking for some ideas from more experienced ones than I am in functional programming.

I understand that the main motivators for keeping everything unchanged make things more understandable and stop errors from creeping to parallel tasks. The disadvantage of this is that every time you want to make changes to the data structure, you need to copy the entire data structure to a new object, but with the desired change. Presumably, there are some operational costs for this: although I would not think twice about doing this for a small object, surely it becomes incredibly slow if you work on large matrices or tensors or similar large data structures?

In short:

  • Is there a performance limitation for copying immutable data structures and how important is it?
  • If so, can you give an example of where you (personally) could draw a line between creating something immutable and turning it into mutability?
+4
source share
3 answers

I understand that the main motivators for keeping everything unchanged make things more understandable and stop errors from creeping to parallel tasks.

This may be the main motivation. But there are other benefits. But this can lead to increased productivity. For example, lockfree and waitfree datastructures are a way of processing parallel processing and are aimed at reducing the overhead of locking.

, , , , .

. . , . O (d) ( d) . , ​​ .

, - (, , ).

, , , . , . , . , , , , . , , , , - , .

- ?

, Haskell, . , , . Haskell , .

+6

, , "" . , , - , . .

Clojure :

Clojure . , Clojure "" , , .

( )

,

[0 1 2]

()

(conj [0 1 2] 3)

3 . 3 , . "" 3.

? . . , . 99% , 1%, (, UI). , .

, .

+3

, , , , .

. ( , , ), .

eg. consider this binary tree:

    |
    a
   / \
  b   c
 / \ / \
d  e f  g

If you want to change the value in node c, you only need to create modified copies aand c:

    |
    a'
   / \
  b   c'
 / \ / \
d  e f  g

The rest of the structure can be reused. Fixed nodes are split between different versions of the tree. This separation is safe precisely because of immutability.

+3
source

Source: https://habr.com/ru/post/1689121/


All Articles