Non-mutating data references in Val #750
Replies: 0 comments 5 replies
-
There are several ways to approach your use case without reference semantics. First, you can represent a range with a pair of positions in a collection and use the collection to get accessed to the referred span. For example:
The key here is that we are not storing access to the data structure in another object, so as to respect the whole/part relationships of our program. Second, you can get spans if you use projections in Val. For example:
To preserve value semantics, however, you cannot uncomment line 3. Notice that both solutions satisfy your requirements. They are safe and efficient. Nothing got copied.
Well, it turns out that managing lifetimes is actually a rather difficult exercise that even experienced software developers can get wrong. The advantage of value semantics is that it prevents mistakes by design because the compiler always catches them. |
Beta Was this translation helpful? Give feedback.
-
Thanks @kyouko-taiga for an in-depth reply. The solution with indices would be also my first approach (and I use it extensively in my own software). But it does come with a somewhat annoying overhead of having to explicitly supply the data buffer every time the value is needed (on that note, I often dream about a fast and efficient language with statically checked dependent types but I digress...) Projections would be the ideal solution, but only if projections could "escape" the local scope and be copied and stored elsewhere. I don't suppose that designing a compiler that could track projections across multiple data structures and complex code is even feasible. |
Beta Was this translation helpful? Give feedback.
-
I am trying to understand what limitations are there to the value semantics in Val.
Consider a common problem where one has to parse some in-memory data buffer (e.g. contents of a source file) and then perform some operations on the resulting structure. It is desirable that the parser output contains the location of the relevant span in the original data buffer which can be either used for further processing or user diagnostics. In a language that supports references I would use a span-like construct (pointer + length) that points into the original data and does not allow mutability. This is safe (no mutation = no problem), efficient (no data copies) and easy to reason about (clear ownership structure). There is of course the challenge of managing the lifetimes, but that is mostly an exercise in good software design.
Would it be possible to implement a similar pattern in Val or does value semantics dictate that each span must be a separate copy?
Beta Was this translation helpful? Give feedback.
All reactions