Reputation: 29159
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
| _ ->
.....
Upvotes: 4
Views: 984
Reputation: 8551
In this particular case, you could also 'invert' the branches:
match date with
| Some s when s > aDate ->
.....
| _ ->
..... // Part 1
Upvotes: 3
Reputation: 233150
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"
Upvotes: 6
Reputation: 157
You just forgot the arrow -> in the None case
match date with
| None ->
..... // Part 1
| Some s when s <= aDate ->
..... // repeat Part 1
| _ ->
.....
Upvotes: -2