gleam
gleam copied to clipboard
Field and recursive access in guard tests
Probably just enqueuing more work for myself, but...
For case guard expressions, the parser appears to limit you to using variables and integer indexed values of tuple variables, so your options are pretty much limited to:
case thing {
a if a.1 == 5 -> True
b if b < 4 -> False
// etc
}
This is well and good, but it's an arbitrary constraint. Erlang supports record syntax in guards, so there's no reason why we can't support named field access:
case cat {
c if c.name != "Nubi" -> True
// ...
}
Though, this could be done via pattern-match instead:
case cat {
Cat(name: name) if name != "Nubi" -> True
//...
}
But the same could be said for integer-based indexing of tuples, so :shrug:
Also, recursive access could be supported, if desired:
case thing {
a if a.1.foobar != 5 -> True
b if a.1.2.3.4 == 6 -> True
// ...
}
We definitely want this! Thank you
As a potential extension of this in the general notion of "things I expected to work in guard tests but didn't": arithmetic operators. For instance (contrived, again, of course):
case x {
y if y * 5 > 20 -> True
// ...
}
Yields this error message:
error: Syntax error
┌─ src/testapp.gleam:13:12
│
13 │ y if y * 5 > 20 -> True
│ ^ I was not expecting this.
Expected one of: "->"
Generally anything that works in Erlang guards and Gleam has a literal expression syntax I'd be happy to add to Gleam's guard
I'd like to try my hand at this. I think to start I'll just add support for named field syntax and go from there.