How might one dynamically access a struct?
Such as (struct-{calculated} struct)
you usually don’t; structs are fairly static by design. but maybe if you explain what you’re trying to do we can give a better answer.
I’ll try to hide the details of my problem, but I’ve mapped numbers onto letters of the alphabet in a struct
And now I would like to dynamically access the values
I wish to create a function that does letter->number
And I thought a function that looks up a struct literal was the most fitting representation
@slack1 the opposite direction (e.g. number->whatever
is easier to think about. That’s whatvector
s are for.
I think a dictionary would be a better fit than a struct the other way
In the forward direction, is reach for a hash / dict first.
Ah, I just thought that a struct was an immutable dictionary / hash
I think they’re implemented with vectors, actually.
Not sure when Racket does the name-to-index lookup for you.
What’s the difference between an immutable hash and a struct?
Aside from access semantics and pre-included methods
I’d say it’s that a hash can have keys of anything hashable, but the “keys” of a struct are just symbols
Oh I see that’s an interesting distinction
I guess I might also ask, how do people differ between arrays and vectors?
Whether immutable / growable
I’d say arrays are best if you’re doing things like slicing, flipping, merging, or folding over elements, especially if you need 2d or 3d arrays
vectors work best if you just need constant time random access by index and don’t care much about other sorts of operations
and generally I prefer to stick an immutable data structure in a mutable box instead of using a mutable data structure
so I’ve yet to find a use for growable vectors
It helps to remember that arrays are in the math library, and come with a lot of linear algebra operations.
You can think of a hash as a normal array (Racket vector) that uses a “hashing” function to translate keys into numeric indices.
@slack1 have you considered using an association list, or “alist,” instead of a hash or struct? Alists are a LISP/Scheme idiom, so the base library has excellent support for them. It may also be the most efficient solution to your problem.