The following code try to combine two match cases None
and Some s when s <= aDate
(Do "part 1" if date is None or date <= aDate).
match date with
| None
| Some s when s <= aDate ->
..... // Part 1
| _ ->
.....
However it get the error? How to avoid rewrite "Part 1" twice?
The two sides of this 'or' pattern bind different sets of variables
The following code works.
match date with
| None ->
..... // Part 1
| Some s when s <= aDate ->
..... // repeat Part 1
| _ ->
.....
I don't think you can do that, for the reason explained by the compiler error.
However, you should be able to solve the duplication with an active pattern:
let (|IsPart1|_|) aDate candidate =
match candidate with
| None -> Some ()
| Some s when s <= aDate -> Some ()
| _ -> None
This would enable you to write a function like this:
let foo date aDate =
match date with
| IsPart1 aDate -> "Part 1"
| _ -> "Part 2"
Here are some FSI usage examples:
> let aDate = DateTime(2015, 7, 29);;
val aDate : DateTime = 29.07.2015 00:00:00
> foo None aDate;;
val it : string = "Part 1"
> foo (Some (DateTime(2011, 1, 1))) aDate;;
val it : string = "Part 1"
> foo (Some (DateTime(2015, 7, 30))) aDate;;
val it : string = "Part 2"
In this particular case, you could also 'invert' the branches:
match date with
| Some s when s > aDate ->
.....
| _ ->
..... // Part 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With