#Restrict parameter to only a defined set of possible elements
14 messages · Page 1 of 1 (latest)
Can you elaborate on what you want to accomplish? The answer could be different depending on that
yeah, at some level you’re just describing: ```rs
fn foo<T>(v: Vec<T>) { /* ... */ }
yes so it would act like a type but defined at runtime. The caller will provide the set of the different elements of the type, the "alphabet", and then i want functions to only accept values of this alphabet as parameters, but i don't want to check every time if the value is in the alphabet
You could have a wrapper type that can only be constructed with a value, and a reference to the set and only creates an instance if the value is in the set. That way if you have an instance of the wrapper you know it has been checked before and found in the set
Oh I see, so like I have a struct Symbol with a method new that checks if the value passed is a valid symbol
and each instance of the wrapper should have a reference to the alphabet then?
Yeah, if the wrapper has a shared reference to the hashset it was checked against that ensures it can't change afterwards too
that makes sense thanks
that'd act like a smart pointer
@cedar pendant but then, I'd have to specify the alphabet every time i'd want to create a new symbol?
Yeah, it might not work out as I was first thinking because you also need to encode the alphabet at the type level rather than just the value level for a symbol
Hmm....the other option is if you know the alphabet at compile time, you could encode that as an enum and the vec could just be a vec of the enum type
yeah i don't know the alphanet at compile time
Hmm, yeah the problem I can see is that if it's not known at the type level then you can't distinguish between two symbols created from different alphabets...so the vec could be Vec<Symbol<'hashset, ElemType>>
Which would let you verify that the vec contains elements that were found in some set, and they could have a shared reference to that set inside to stop mutation
Don't think there would be any way to prevent symbols from two different sets being mixed in the vector though...