Hi Rowan On Tue, Mar 19, 2024 at 8:39 PM Rowan Tommins [IMSoP] <imsop....@rwec.co.uk> wrote: > > As well pattern matching, which Ilija mentioned, another adjacent feature is > a richer set of casting operators. Currently, we can assert that something is > an int; or we can force it to be an int; but we can't easily say "make this > an int if safe, but throw otherwise" or "make this an int if safe, but > substitute null/$someValue otherwise". > > I've been considering how we can improve that for a while, but not settled on > a firm proposal - there's a lot of different versions we *could* support, so > choosing a minimal set is hard.
I've thought about this in the context of pattern matching a while back. I was thinking about something like `$x is ~int`, where the pattern match is successful iff `$x` is coercible to `int` without loss of information. Given that patterns may be nested, `array<~int>` could check that all elements of an array are coercible to `int`. The same could work for literal patterns, e.g. `~5`, where `5`, `5.0` and `'5'` are all accepted. This can potentially be combined with the variable binding pattern, `$var @ pattern`. The syntax looks a bit confusing at first, but it basically makes sure that the matched value conforms to `pattern`, and then binds it to `$var`. Hence, something like `$foo as Foo { $bar @ ~int }` would 1. make sure `$foo` is an instance of `Foo`, 2. make sure `$foo->bar` is coercible to `int`, and then assigned the coerced value to `$bar`. (It gets more complicated, because the assignment must be delayed until the entire pattern matches.) If the pattern matching fails at any point, it throws. This is just an idea, neither the `as` operator nor the `~` pattern have been implemented. I don't know whether they are feasible. Anyway, we're probably going off-topic. :) Ilija