Compliance of F # to a template .Net-constants

The code in the following example

open System.Drawing

let testColor c =
    match c with
    | Color.Black -> 1
    | Color.White -> 0
    | _ -> failwith "unexpected color"

not compiled. The error Error 1 The field, constructor or member 'Black' is not defined.

How do I match a pattern with .Net constants or enumerations starting with capital letters?

For what it's worth, the compiler is "Microsoft (R) F # 2.0 Interactive build 4.0.30319.1."

+2
source share
2 answers

You cannot match a pattern with arbitrary values ​​of an object. Use the conditions if then elseor when:

let testColor c = 
    match c with 
    | c when c = Color.Black -> 1 
    | c when c = Color.White -> 0 
    | _ -> failwith "unexpected color"
+5
source

, - , switch. , . Active Patterns , Black, White Other . "" , . ,

open System.Drawing
let (|Black|White|Other|) (color:Color) =
    if color = Color.Black then Black
    elif color = Color.White then White
    else Other

let testColor c =
    match c with
    | Black -> 1
    | White -> 0
    | Other -> failwith "unexpected color"

, , , 1 0, :

let (|KnownColor|_|) (color:Color) =
    if color = Color.Black then Some(1)
    elif color = Color.White then Some(0)
    else None

let testColor2 c =
    match c with
    | KnownColor i -> i
    | _ -> failwith "unexpected color"

switch, :

let (|Equals|_|) (lhs) (rhs)  =
    if lhs = rhs then Some(lhs) else None

let testColor3 c =
    match c with
    | Equals Color.Black _ -> 1
    | Equals Color.White _ -> 0
    | _ -> failwith "unexpected color"

let testString c =
    match c with
    | Equals "Hi" _ -> 1
    | Equals "Bye" _ -> 0
    | _ -> failwith "unexpected string"
+11

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


All Articles