-
Lesson I learned today: imperative languages can't express data structures that are both immutable *and* circular. For example, you can't build an immutable, doubly linked list in #csharp without ugly runtime assertions. 🤮
-
The reason for this is because you can't construct an immutable object without having all its dependencies first. So if A <-> B, you can't construct A without B, but you also can't make B without A.
-
Mutability works around this because you can just construct A without a reference to B (such as
null
) then add it later once you've made B. This made me wonder, are there other languages which can provide a compiler-guaranteed immutable *and* circular data structure? 🤔 -
Like most esoteric #ComputerScience problems, the answer is: functional programming languages. For example, #Haskell does this by "tying the knot", leveraging laziness to define two symbols that reference each other. 🤯 wiki.haskell.org/Tying_the_Knot