Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type narrowing in case expressions #2060

Open
despairblue opened this issue Mar 10, 2023 · 1 comment · May be fixed by #3647
Open

Type narrowing in case expressions #2060

despairblue opened this issue Mar 10, 2023 · 1 comment · May be fixed by #3647
Labels
help wanted Contributions encouraged priority:low

Comments

@despairblue
Copy link
Contributor

Was wondering if this could be added to the compiler:

pub type Being {
  Person(name: String, age: Int, is_happy: Bool)
  // imagine this type having a gazillion fields
  Dog(name: String, age: Int, is_happy: Bool)
}

pub fn have_birthday(being) {
  // It's a birthday, so increment their age and make them happy
  case being {
    Dog(..) as dog -> Dog(..dog, age: dog.age + 1, is_happy: True)
    Person(..) as person ->
      Person(..person, age: person.age + 1, is_happy: True)
  }
}

This leads to

[gleam] error: Unsafe record update
   ┌─ ./src/playground.gleam:10:23
   │
10 │     Dog(..) as dog -> Dog(..dog, age: dog.age + 1, is_happy: True)
   │                       ^^^ I can't tell this is always the right constructor

This type has multiple constructors so it cannot be safely updated.
If this value was one of the other variants then the update would be
produce incorrect results.

Consider pattern matching on it with a case expression and then
constructing a new record with its values.

Now I already pattern-matched on it and the compiler could know it's a dog. If the Dog would have lot's of fields then writing out every field becomes tedious.

@lpil
Copy link
Member

lpil commented Mar 10, 2023

A fab suggestion! We would need to implement #34 first before this type narrowing feature.

I'm sure we had an existing issue for this but I can't find it now unfortunately.

@lpil lpil added help wanted Contributions encouraged area:analysis labels Mar 10, 2023
@lpil lpil changed the title Permit updating records with multiple constructors if the constructor is known Type narrowing in case expressions Jul 22, 2024
@GearsDatapacks GearsDatapacks linked a pull request Sep 25, 2024 that will close this issue
3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Contributions encouraged priority:low
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants