#Restrict parameter to only a defined set of possible elements

14 messages · Page 1 of 1 (latest)

plucky coral
#

Hi, I want to create a function that takes a set of possible elements, and then a vec containing only elements in that set. Is it possible to do it statically and not having to check if all elements of the vec are defined in the set?

faint hare
#

Can you elaborate on what you want to accomplish? The answer could be different depending on that

gleaming cairn
#

yeah, at some level you’re just describing: ```rs
fn foo<T>(v: Vec<T>) { /* ... */ }

plucky coral
#

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

cedar pendant
#

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

plucky coral
#

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?

cedar pendant
#

Yeah, if the wrapper has a shared reference to the hashset it was checked against that ensures it can't change afterwards too

plucky coral
#

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?

cedar pendant
#

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

plucky coral
#

yeah i don't know the alphanet at compile time

cedar pendant
#

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...