Matching a function call discriminatory union pattern

My question is inspired by this: link

Here is the code:

    type A = 
        | X of int * int
        | Y of string

    let f (A.X(a, b)) = a + b 

This works, but with a warning: warning

Has the meaning; I have no match for Y.

But if I add a line

    let f (A.Y(s)) = 10

Then I get the error message:

error

Is there a good way to fix it and still use pattern matching in function parameters? If not, why did they create such a strange syntax that always leads to a warning?

+4
source share
3 answers

You need to match the pattern by argument:

let f = function
| X(a, b) -> a + b
| Y(_) -> 10

When you define

let f (A.X(a, b)) = a + b 

f A -> int, A.X -> int. , A.Y, .

f A -> int, , , . - , function match.

EDIT: , , , match :

let f a1 a2 =
    match (a1, a2) with
    | (X(a, b), X(a', b')) -> a + b
    | (X(a, b), Y(s)) -> a + 10
    | (Y(s), X(a, b)) -> 10
    | (Y(s), Y(s')) -> 20
+8

, . fst , 2 .

let fst (a,_) = a

:

type Container = Container of string
let unwrap (Container(v)) = v

type Person = { Name:string; Age:int }
let getName {Name=name} = name
+4

, function match.
, F # - . , . .

let f ((A.X(a, b), _ ) | (A.Y(_), (a, b))) = a + b

// usage
let x1 = f(A.X(10, 42), (100, 1)) // x1 = 52
let x2 = f(A.Y("foo"),  (100, 1)) // x2 = 101

?

  • ;
  • A.X, ;
  • The function takes an additional argument, which can be considered a fallback value. Namely, when the first argument A.Y(string), we still need to summarize something.
  • The return value is ignored if the first argument has some value value A.X(int, int).

Again, do not use it blindly in real projects, as it does not seem readable.

Further reading: A similar approach for list processing .

+2
source

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


All Articles