Argument datatype dependant of previous arguments?
While working with a dynamically typed lang, I came across this:
<span style="color:#323232;">hash(password, algorithm, algorithmOptions)
</span>
Where algorithm
is a constant signaling which hashing algorithm to use, and algorithmOptions
is a dict whose keys depend on algorithm
.
So I thought, can we dictate that if a previous parameter has this value, then this parameter has to have this other value?
E.g.
<span style="color:#323232;">enum HashAlgo {
</span><span style="color:#323232;"> Bcrypt,
</span><span style="color:#323232;"> Argon2,
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="color:#323232;">type BcryptOptions = {
</span><span style="color:#323232;"> Int optionA,
</span><span style="color:#323232;"> Int optionB,
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="color:#323232;">type Argon2Options = {
</span><span style="color:#323232;"> String optionC,
</span><span style="color:#323232;"> String optionD,
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="color:#323232;">
</span><span style="color:#323232;">// Here I make this type "depend" on an argument of type HashAlgo
</span><span style="color:#323232;">type HashOptions = [HashAlgo] => {
</span><span style="color:#323232;"> HashAlgo::Bcrypt => BcryptOptions,
</span><span style="color:#323232;"> HashAlgo::Argon2 => Argon2Options,
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="color:#323232;">fun hash(
</span><span style="color:#323232;"> String password,
</span><span style="color:#323232;"> HashAlgo algorithm,
</span><span style="color:#323232;"> // Here I use HashOptions, passing the prev. argument
</span><span style="color:#323232;"> HashOptions[algorithm] options,
</span><span style="color:#323232;">)
</span>
This way the compiler can ensure the correct dict is used, based on the value of algorithm
Does something like this exist? I now realize that it would be impossible to type check in compile time based on a runtime value, but if it was allowed only for constants? What do you think?
Add comment