Multiple match arms with options?

I’m trying to match a (string * string) list, with multiple guards for each arm of the match – something like

match x with
| [("a", a); ("b", b)] | [("a", a)] -> (* Some code here, where b is Some string if the first condition holds or none in the second *) ()
| _ -> () (* Other cose here *)

I guess this is possible by matching twice,

let t = (match x with | [("a", a); ("b", b)] -> (a, Some(b)) | [("a", a)] -> (a, None), | _ -> () (* Code to handle this case *))
in (* Code that handles this case *) ()

but I was wondering if there’s any kind of syntactic sugar which might make this easier?

p.s. apologies for first posting this in a half-finished state and then editing it three times – I had some problem where I was accidentally using a keyboard shortcut to publish rather than create a new line

No syntactic sugar, but perhaps a local function?

let f a b = ... in
match x with
| ["a", a; "b", b] -> f a (Some b)
| ["a", a] -> f a None
| _ -> ()

Cheers,
Nicolas

1 Like