简体   繁体   中英

How to do pattern match on fields of 2 records?

type A =
  {
    ...
    id: int;
    ...
  }

I wish i could do this

let Add (x:A) (y:A) =
     match x,y with
      | {x.id=0,y.id=1} -> ...

And is there any trick to define the function if i don't care about the order of x and y (so that the function is symmetric) also i don't mind whether the parameter is a tuple (x,y) or a higher order function x,y

Another syntax for this is:

let add x y =
    match x, y with
    | {id = 0}, {id = 1} | {id = 1}, {id = 0} -> ..
    | _ -> ..

See Record Pattern section at http://msdn.microsoft.com/en-us/library/dd547125.aspx

let add (x: A) (y: A) =
     match x.id, y.id with
     | 0, 1 | 1, 0 -> (* do some thing *)
     | _ -> (* do some thing else *)

If you only care about a field, do pattern matching directly on it. And you can use Or pattern to have a symmetric function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM