gleam icon indicating copy to clipboard operation
gleam copied to clipboard

Field and recursive access in guard tests

Open J3RN opened this issue 3 years ago • 3 comments
trafficstars

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

J3RN avatar Dec 29 '21 05:12 J3RN

We definitely want this! Thank you

lpil avatar Dec 29 '21 09:12 lpil

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: "->"

J3RN avatar Dec 29 '21 21:12 J3RN

Generally anything that works in Erlang guards and Gleam has a literal expression syntax I'd be happy to add to Gleam's guard

lpil avatar Dec 29 '21 21:12 lpil

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.

bcpeinhardt avatar Apr 12 '23 23:04 bcpeinhardt