Join GitHub today
GitHub is home to over 31 million developers working together to host and review code, manage projects, and build software together.Sign up
Multiple pattern cases with 'when' clauses #715
Multiple pattern cases with 'when' clauses
I propose we allow multiple patterns with 'when' to be or'ed together.
The existing way of approaching this problem in F# is using an if-statement or even duplicated code.
Consider the following code:
type internal 'T memory = System.Memory<'T> type internal chars = char memory [<Struct>] type UnicodeCharacter = private UnicodeCharacter of chars module UnicodeCharacter = let Create (x:chars) = match x.Length with | 1 when x.Span. |> System.Char.IsSurrogate |> not | 2 when x.Span. |> System.Char.IsHighSurrogate && x.Span. |> System.Char.IsLowSurrogate -> x |> UnicodeCharacter |> ValueSome | _ -> ValueNone let (|UnicodeCharacter|) (UnicodeCharacter x) = x
Currently the F# compiler errs out with the message
I propose that we allow this instead of having to duplicate the case handling code, with a slight syntax change because
match x.Length with | 1 when x.Span. |> System.Char.IsSurrogate |> not -> | 2 when x.Span. |> System.Char.IsHighSurrogate && x.Span. |> System.Char.IsLowSurrogate -> x |> UnicodeCharacter |> ValueSome | _ -> ValueNone
Pros and Cons
The advantages of making this adjustment to F# are more conciseness, less typing, less cognitive load!
The disadvantage of making this adjustment to F# is that as with any syntax change, we might be making F# more complex.
Estimated cost (XS, S, M, L, XL, XXL): S
Related suggestions: Couldn't find any, please point it if any
Affidavit (please submit!)
Please tick this by placing a cross in the box:
Please tick all that apply:
We can create
Your example can be then written as:
@jindraivanek Unfortunately that doesn't actually work because for some reason active pattern inputs can't be arbitrary expressions. For instance they don't seem to support infix operators. With
@theprash Thanks for pointing that out, wasn't aware that infix operators didn't work in patterns. Looks like also other things don't work, like lambdas or indexing. Basically only function calls and other patterns are allowed. I don't see why any expression shoudln't be allowed, because you can do it by calling custom function. Agree it would be good addition.
So, my workaround is not helping much here.
Another possibility might be to extend array pattern syntax to System.Memory. If that were possible, you could do something like;
Edit: Actually, I guess if the array pattern syntax is extended, it should be extended to Span, with support for implicitly casting arrays to Span when used in pattern matching.