Functional programming: state vs. reassignment

后端 未结 4 1632
星月不相逢
星月不相逢 2020-12-13 07:44

I need help getting my head around the difference between my current OOP notion of state, and the way it would be done in a functional language like Haskell or Clojure.

4条回答
  •  一整个雨季
    2020-12-13 08:28

    So... what do I do with it? Overwrite whatever variable was referencing the old bank-account?

    Yes

    If so, does that have advantages over the state-changing OOP approach?

    Let's say the computation of whatever action you do on that struct takes a long time and something happens midway and you need to revert back to the original struct or the computation raised an error. With the interpretation you've presented to me of OO (using a reference, because you can have an immutable OO language) that data could be corrupt --it's unknown unless enough information was given from the failed function call, and lets suggest it failed badly. In a functional approach you know for sure that your original data structure is correct --because you initially made a copy.

    Extend this scenario in multi-threaded applications. We can ensure that no one else is using the data structure we are since we all have our own version of it.

    Additionally, we can save space by using data from the other structure that we are copying from. A classic example is when adding an element to the head of a list. If we have a pointer to the second element, and a pointer to the first element we can reference both lists with only the size of the first (see below). Without immutability we cannot guarantee this.

            b__
               |  
    a -> [6|] -+-> [5|] -> [4|] -> [3|] -> [2|] -> [1|x]
    

提交回复
热议问题