What is the benefit of purely functional data structure?

前端 未结 5 1015
南方客
南方客 2020-12-12 14:27

There are large number of texts on data structures, and libraries of data structures code. I understand that purely functional data structure is easier to reason about. Howe

5条回答
  •  情书的邮戳
    2020-12-12 14:46

    In addition to shared memory safety most purely function data structures also give you persistence, and practically for free. For example, let's say I have a set in OCaml, and I want to add some new values to it I can do this:

    module CharSet = Set.Make(Char)
    let a = List.fold_right CharSet.add ['a';'b';'c';'d'] CharSet.empty in
    let b = List.fold_right CharSet.add ['e';'f';'g';'h'] a in
    ...
    

    a remains unmodified after adding the new characters (it only contains a-d), while b contains a-h, and they share some of the same memory (with a set it's kind of tricky to tell how much memory is shared since it's an AVL tree and the shape of the tree changes). I can continue doing this, keeping track of all the changes I've made to the tree allowing me to go back to a previous state.

    Here's a great diagram from the Wikipedia article on Purely Functional that shows the results of insert the character 'e' into the binary tree xs:

    alt text

提交回复
热议问题