Using a specific type variant as a parameter type #4098
Closed
dandeduck
started this conversation in
Ideas & suggestions
Replies: 1 comment 1 reply
-
It's certainly not impossible to implement this, but this is not going to be added to the language. People have brought it up time and time again, but it's not an oversight or impracticality, but a conscious design choice. Variants are not types, they are values. // This type represents the possible states of some data
type Wibble {
Wibble(WibbleData)
Wobble(WobbleData)
}
// This type only has one variant, so you can always perform record access on it!
type WibbleData {
WibbleData(...)
}
// Same for this one
type WobbleData {
WobbleData(...)
}
fn do_something(wibble: Wibble) {
case wibble {
Wibble(data) -> handle_wibble(data)
Wobble(data) -> handle_wobble(data)
}
}
fn handle_wibble(wibble: WibbleData) {
wibble.some_field // This is valid
}
fn handle_wobble(wobble: WobbleData) {
wobble.some_other_field // This is valid
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Disclaimer
I'm pretty new to Gleam, so please let me know if I'm missing something, or if there is a better way to achieve what I'm doing.
Problem
I often run into situation where I have an entry function that receives a record with multiple variants, does pattern matching and calls the relevant function. So far, I had to deconstruct each variant and pass those properties to the function since Gleam doesn't adjust the type of a variable after it was pattern matched (which I get). Example:
This is a bit annoying, especially when this data might have to go through multiple functions. Of course I can create an additional type just for this, but it feels a bit redundant.
Suggestion
I realize that it's not good do the TS craziness where types dynamically change according to context, but I thought something like this can be done:
(I use
>
as a placeholder)Behind the scenes it might create a "special type" that represents the variant, since it's being used as a type here.
This might be impossible/impractical, just writing what comes to my head 😛 Please share your thoughts!
Beta Was this translation helpful? Give feedback.
All reactions