'Chaining clauses in a pattern match, how to add missing bindings
I have a type defined as such:
type quantity = Value of int | Direction of int * int | Vector of int * int * int
Later I have functions that operate on values of the latter two subtypes together:
match q with
| Direction(x, y)
| Vector(x, y, magnitude) ->
Is there some way of defining magnitude to be 0 if the first pattern is matched? I know that I can use let x, y, magnitude = match (...) to convert the type into a tuple, or combine Vector and Direction into one subtype, setting magnitude to 0 where appropriate.
But I am looking for something concise.
Solution 1:[1]
I am not sure that I understand your question. If the first pattern matches then quantity is of the direction subtype, so there is no vector. So depending on what you're asking it could be something like this,
match q with
| Direction (x,y)
| Vector (x,y,0) ->
which will match with either a direction or a vector that has zero magnitude.
Alternatively, if by "defining a magnitude to be 0" you mean creating a vector with zero magnitude to which a direction should be mapped, then it could be done as,
match q with
| Direction (x,y) -> Vector (x,y,0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ivg |
