using sys { Map }
class Pt{ // A user-def class.
x = 0; // Its fields
y = 0;
call(ax, int, ay int) this { x:= ax; y := ay } // One of constructors.
}
m = Map(String, Pt) // Declare map with string keys and Pt values.
("Alpha", Pt(1, 2)) // Fill it with data.
("Bravo", Pt(-1, 42));
log(
m["Aplha"] // Access element by key.
? `Pt(${_.x}, ${_.y})` // Check it and convert to string.
: `Not found`); // Handle if no such element.
This will output: Pt(1, 2).
Maps are not built-in entities in Argentum, in fact even Arrays are not built-in. They are all mere classes of standard library. And since all Argentum classes are extendable, you can always add arbitrary methods to arrays and maps.
m.each() k v {
log(`key: ${k} x: ${v.x} y: ${v.y}`);
}
In this example `each` is the ordinary method implemented for map class in one of `utils` modules.
Any user type can be a key.
Argentum:
- supports user-defined hash-functions
- caches the once-computed hash in the object header
- provides built-in hash for strings and address-based hash for generic objects.
Map class requires keys to be frozen objects. This prevents from common error in other languages then by modifying map keys a map can be brought to incoherent state.
There are owning maps, maps of weak pointers and maps of shared pointers to immutable objects. So maps follow all Argentum rules of object composition, sharing and thread-safe handling - so no races, no crashes, no overheads. And topology aware copy operation supports map as well:
m1 = @m; // Makes a full deep copy of the map
This code not only copies the map along with all its values (keys are shared since they are immutable) but also it handles cross-references between map elements preserving object graph topology. In other languages this operation requires peculiar hand-written code, while in Argentum it's automated.
Internally Maps are implemented as flat, open addressed, 2^n grow, linear probe, robin hood hash-tables. So they are fast and not that much memory consuming.
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.