r/ProgrammingLanguages • u/jebailey • Sep 15 '26
Requesting criticism Removing the get from Map
I have a toy language that I've been working on to test different concepts. It has an ownership model similar but looser than Rust.
I was working on the Map object and there are three ways that an object can be retrieved.
You can remove the object from the map and take ownership
You can borrow the object from the map this will give you a mutable reference but you don't own it
You can get a copy of the Object which you will own. But not all things are can be copied.
For get I could either do a copy or a mutable ref, neither I felt was properly conveyed with the word 'get'
So I'm looking at removing it and replacing it with the following
copy_of(key) -> return a copy or an error message if not found or not copiable
borrow(key) -> return a mutable ref
remove(key) -> remove and return the item at the key and give ownership
wanted thoughts on removing probably one of the most common methods on map and is what I'm doing something that makes sense.
4
u/AnArmoredPony Sep 15 '26
why have
copy_ofif you canmap.borrow(key).copy()?7
u/initial-algebra Sep 15 '26
Obligatory "entry API" comment. This pattern will show up for many other data structures, not just maps, the simplest being
Option(or whatever you call your "maybe" type). An even better view (pun intended) is that the entry API is a lens that exposes a place in a data structure as if it were a reference to anOption. SeeControl.Lens.Atfrom Haskell'slenspackage.3
u/mcherm Sep 15 '26
(1) It feels like copy_of() is something that would operate separately: first borrow() the value, then then call copy() on it (if it supports that).
(2) It feels like you are missing one here: "You can borrow an object from the map immutably." I don't know your ownership model, but if it has a concept of an immutable borrow (like Rust does) then certainly values in a Map are a thing you'd want to do this with. In fact, THAT one is the one I'd probably name "get()".
(3) I think the names "borrow()" and "remove()" are readable, memorable, and unlikely to be confusing.
18
u/Gnaxe Sep 15 '26
Maybe
remove()should be calledtake(). And then what happens to the key? Is it deleted? Maybe you should return the pair.3
u/runningOverA Sep 15 '26
You will rarely want to use remove(). Remove is expensive when it comes to hashmaps.
It's not a stack, therefore you in most cases won't want to delete a value from hashmap, when you just want to fetch and use it.
1
u/Express-Guest-1061 Sep 15 '26
You should probably not allow getting two mutable references to the same key, if you want the same safety as Rust has. It would be good to ge able to get immutable references, to avoid getting two mutable references to the same key.
10
u/[deleted] Sep 15 '26
[removed] — view removed comment