Named deconstructors that can fail. #4818
Unanswered
mrange
asked this question in
Language Ideas
Replies: 1 comment 1 reply
-
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I asked on twitch about Deconstructors that can fail and Kathleen D suggested I post a question here.
I am looking for Named deconstructors that can fail. I am obviously inspired by F# Active patterns and Scala
unapply
. These are powerful techniques to allow custom pattern matching.My code examples are quite rubbish but I thought it might be better to supply some examples to help start a thinking process.
Example:
I have the need to parse GraphQL, visitor classes are pain. Pattern matching over the syntax tree is preferable IMHO.
I would like my code to look something like this:
The GraphQL syntaxNode has a common base class for all nodes in the syntax tree. With pattern matching you test if the type and extract the relevant variables from the syntax node.
One possible way to implement this could be have
Deconstruct
scoped by a classAnother case for this is to help implement union types. Something I miss dearly from F#, Scala, Haskell and so on.
I have tried to emulate it in existing version of C# but it is clunky
There are also arguments to allow passing input args to Deconstructors.
Very very hand-wavy code
What about type patterns
Supposedly type tests could work as well but pattern matching would be more flexible and if C# supported nested deconstruction that could enable even more powerful ways to traverse a syntax tree.
Links:
Active Patterns F# - https://fsharpforfunandprofit.com/posts/convenience-active-patterns/
Scala unapply - https://www.tutorialspoint.com/scala/scala_extractors.htm
Scala regex unapplySeq - https://www.scala-lang.org/api/2.12.1/scala/util/matching/Regex.html
Beta Was this translation helpful? Give feedback.
All reactions