Simplifying Pattern Matches #103
AttilaMihaly
started this conversation in
Ideas
Replies: 1 comment 2 replies
-
Since the use of Tuples is very limited in business models, we should also consider removing support for arbitrary size tuples and only support pairs using and SDK type instead of direct language support. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Problem Statement
The Morphir IR supports patterns at various places in the logic. Patterns are a powerful construct that can be used to test for equality of values, to deconstruct tuples, tagged unions and lists and they can also be nested to create more complex patterns. This makes them a very convenient tool but the flexibility they provide also makes them challenging to transpile into languages that don't support the same form of patterns.
Proposal
What makes mapping patterns especially challenging is that they cover a wide range of different types and for each type of value patterns are used differently. For tagged unions we usually want to branch out based on the tag, for lists we do that based on the number of items in the list and for some built-in types we are looking for exact equality. If we had a specific construct for each of these, the mapping would become much easier because we would limit the number of possibilities in each case significantly.
Implementation Details
Current pattern definition
Matching tagged unions
A tagged union is represented as a set of constructors in Morphir. Each constructor has zero or many arguments. Since a union represents an "or" relationship between the different constructors it naturally maps to control flow where the logic branches out by tag. Here's a simple way to represent that construct:
Matching lists
When matching lists we want to:
Here's one way to represent such a construct:
Destructuring tuples
Destructuring tuples simply means assigning variable names to its elements. There is no conditional processing or branching involved for this construct.
The simplest way to achieve this is to take a tuple and pass it to a function that has the same number of arguments as many arguments the tuple has. The structure could be as simple as:
To make it easier to understand here's how that would look like in Elm:
Branching out on literal values
The only remaining pattern we need to define a construct for is
LiteralPattern
. We will simply useif/then/else
to represent this for now. We might want to get into branching out by ranges for comparable types in the future.Beta Was this translation helpful? Give feedback.
All reactions