I and @alehander42 started working on adding pattern matching in stdlib. Right now we at ideas brainstorming stage - what is needed, syntax, potential escape hatches for user-defined behavior etc. There have been some discussion in RFC on github - link and on discord/IRC.
Current syntax/planned features are described in linked comment, but mostly feedback is needed for following questions:
Some examples of current syntax:
There is a proof-of-concept I'm working on right now: examples of use for it can be found here . It uses *@ syntax, but I will most likely switch it to keyword-based one.
case someInputJson:
of [all @elem is JString()]:
echo "all ok"
of [any @elem is JString()]:
echo "that's worse, but we can deal with it")
else:
raiseAssert("Expected at least some elements to be json strings !")
Currently any captures all elements in @val, not just first one. I agree this might be confusing, so maybe renaming it to findAll and find might be a good idea.
Indices of matched elements are not accessible in any predicates right now, but that could be fixed by injecting matches: seq[int] in the scope. Do you think it is necessary to do this?
but that could be fixed by injecting matches: seq[int] in the scope. Do you think it is necessary to do this?
Why a seq? any can stop after the first found match.
On input sequence [1,2,3]
So any/all will generate sequence of all elements that match predicate, mostly working like filterIt. Using "filter" as a keyword is not applicable here, because it does not reflect the fact we are testing for patterns and not transforming input.