haskellcopylanguage-agnostictheorylanguage-design

Is there such a thing as a non-copiable type in Haskell?


In short, I'm trying to understand why copying, which is such a fundamental thing in C++ (fundamental in the sense that you, as the programmer, have quite a lot of power in writing code to permit or forbid copies) and I suppose in other languages, seems so elusive to me in Haskell. (This is the reason for and tags, i.e. I'd like to look at the topic from a perspective that allows me to understand it beyond the single language Haskell.)

To some degree, it feels a bit like copying-or-not-copying is an implementation detail of compiler and/or runtime, and that I, as a programmer have no control over it, but I'm not sure that's the correct way to look at it.

I suppose relevant aspects to take in consideration for answering this questions are


If ghc-vis had not been rottening, I'd be probably experimenting with it, but I haven't been able to get it to compile.

To see the broader context which my musing are about, you might want to give a look at this question.


Solution

  • In Haskell, immutability is the default idiom. In a world of immutability, copying can be implemented as aliasing, which is so cheap it isn't even worth thinking about. In particular this is what's done in GHC: everything is a pointer, and "copy" means "make another pointer to the same thing".

    Languages whose idioms stress mutability more make things more complicated, because copying and aliasing can be meaningfully different. Mutations to a copy don't change the original, but mutations to an alias do. In these situations, the exact "depth" into the data structure that you traverse before switching from copying to aliasing is an important tradeoff that you need to be constantly thinking about; more aliasing is faster, but leaves you more open to mutations spreading to places you hadn't expected.