How to match patterns when something is NOT of a particular type

We are all used to pattern matching for cases when something is a particular type, like

match x with
| Y(x) :: tail -> ... // assumes List.head(x) is of type Y(x)

But how can I compare the case when something is not of a certain type? For instance.

match x with
| Not Y(_) :: tail -> ... // List.head(x) is definitely not a Y

Thank!

+3
source share
2 answers

While there is no direct support Not, you can use a partial active template .

type Color = | Red | Green | Blue

let (|NotRed|_|) = function
    | Red -> None
    | color -> Some color

let rec print = function
    | (NotRed head) :: tail -> 
        printfn "%A is Not Red" head
        print tail
    | _ :: tail -> print tail
    | _ -> ()

print [Red; Green; Blue]

Output

Green is Not Red
Blue is Not Red
+4
source

, - , , . _ ( , , , ):

match x with
| Y _ :: tail -> ()
| _ :: tail -> // List.head(x) is definitely not a Y

, , , . , - :

match x with
| (Y _ | (Z (1 | 2 | 3 | 4)) :: tail -> ()
| _ :: tail -> // Excludes all "Y x" and "Z n when n \in 1,2,3,4"

, - , ... , , .

+4

Source: https://habr.com/ru/post/1793888/


All Articles