Manual memory allocation and purity

memory

Language like Haskell have concept of purity. In pure function, I can't mutate any state globally. Anyway Haskell fully abstracts memory management, so memory allocation is not a problem here.

But if languages can handle memory directly like C++, it's very ambiguous to me. In these languages, memory allocation makes visible mutation. But if I treat making new object as impure action, actually, almost nothing can be pure. So purity concept becomes almost useless.

How should I handle purity in languages have memory as visible global object?

Best Answer

I have to disagree with the basic premise.

C++ (to use your example, though the same would apply to C, Pascal, Ada, etc.) doesn't give any real visibility into the heap. You can attempt to allocate some memory, which might succeed or fail -- but you have no visibility into why an allocation succeeded or failed, nor what other allocations may have lead to that success/failure.

In other words, allocating some memory in one place does not have an effect that's directly visible anywhere else. Yes, it's possible one allocation could lead to the failure of another, but 1) noting in portable C++ can put those together, and 2) it's usually next to impossible to make that connection even in a non-portable way.

In the other direction, nothing in Haskell (or any other language) can change the fundamentals involved anyway. Attempting to allocate more memory than is available (even as virtual address space) will fail, regardless of the language. If the user runs another program that hogs all the memory, neither C++ or Haskell (or much of anything else) can do much about that, so an allocation that would succeed in one run may fail in another.

In fairness, I suppose I should add that even though it's not portable, many (most?) heap managers include extra functions to walk the current heap, see what blocks are allocated, etc. Yes, I suppose such a thing could be seen as breaking "purity", but my guess is that people including heap-walking in their software probably aren't bothered a lot by that (and those who really care about purity just don't use that capability.

Related Topic