Including entire record when pattern matching records

Is there a way to include the entire record field when destructuring in a pattern matching clause? Something like this:

type user = { id: string; name: string; address: string }

let find_steve = function
| { id; name }@user when id = "3" or name = "Steve" -> Some user
| _ -> None

I feel like I remember there was a way to do this in general for any kind of destructuring, but I can’t find it now. I’ve been looking for it in the Bucklescript + ReasonML docs and Real World Ocaml but no dice…

If find_steve is applied on a user, you may not need a pattern match( = function |).

utop # let find_steve (u : user) = if = "3" || = "Steve" then Some u else None;;
val find_steve : user -> user option = <fun>

You mean this?

let find_steve = function
| { id; name } as user when id = "3" or name = "Steve" -> Some user
| _ -> None
1 Like

It’s called an ‘alias pattern’:

Ah thanks! I was trying as earlier but it wasn’t working for me – I was trying it in a function declaration (fun { id } as user -> ...)

That should work–maybe needs a pair of parentheses to disambiguate to the parser. I.e. fun ({id} as user) -> ...

That’s odd, I tried that earlier too. I guess don’t code when you’re tired :confused: