Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The two sides of this 'or' pattern bind different sets of variables?

Tags:

f#

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
| _ -> 
    .....
like image 815
ca9163d9 Avatar asked Mar 16 '23 06:03

ca9163d9


2 Answers

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"
like image 169
Mark Seemann Avatar answered Mar 17 '23 21:03

Mark Seemann


In this particular case, you could also 'invert' the branches:

match date with
| Some s when s > aDate -> 
    .....
| _ -> 
    ..... // Part 1
like image 39
CaringDev Avatar answered Mar 17 '23 19:03

CaringDev