If you can't change a variable's value in Haskell, how do you create data structures?

前端 未结 3 753
醉话见心
醉话见心 2021-02-02 17:58

As per the title.

I have the following code which creates a binary search tree, but if I want it created and changed dynamically with user input, how would I do that if

3条回答
  •  梦如初夏
    2021-02-02 18:31

    You allocate a new tree node and the old one sticks around. This technique requires a really good allocator, but it enables all sorts of nifty devices because other parts of the program still have access to old nodes. This is a godsend for certain kinds of speculative algorithms or other tricks involving so-called "persistent data structures".

    Eventually you allocate a new root for your tree and what then? As Dario says, you pass it as a parameter to a function (instead of storing it in a global variable).

    So

    • Mutation of a field in a struct allocated on the heap becomes allocation of a new struct on the heap.

    • Mutation of a global variable becomes passing a parameter to a function

    Sometimes it also makes sense to take what would have been a collection of global variables in C and put them all in an object allocated on heap.


    P.S. If you really want to, you can have mutable global variables in Haskell. It is, after all, the world's finest imperative programming language (according to Wadler or Peyton Jones, I forget whom). But if you are asking this question, you really don't want to. Yet.

提交回复
热议问题