Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Record pattern matching

According to this accepted answer, in F# and OCaml I need to use underscore for discarding the rest of the record. However, why does the handle' function work but handle function doesn't?

type Type = Type of int

type Entity =
    { type' : Type
      foo : string }

let handle entities =
    match entities with
    | {type' = Type i; _ }::entites -> ()
    | [] -> ()

let handle' entities =
    match entities with
    | {type' = Type i }::entites -> ()
    | [] -> ()
like image 498
MiP Avatar asked Mar 10 '26 18:03

MiP


1 Answers

It's probably not helpful to treat OCaml and F# as the same language. Your code is invalid OCaml for several reasons.

But you're right, the _ is not necessary in OCaml. It is useful if you want to get a warning for incomplete record patterns. If you mark intentionally incomplete record patterns with _ and turn on warning 9, then record patterns without _ will be flagged if they don't specify all the fields of the record.

$ rlwrap ocaml -w +9
        OCaml version 4.03.0

# type t = { a: int; b: string};;
type t = { a : int; b : string; }
# let f {a = n} = n;;
Warning 9: the following labels are not bound in this record pattern:
b
Either bind these labels explicitly or add '; _' to the pattern.
val f : t -> int = <fun>

It was fairly hard to find the documentation for this. You can find it in Section 7.7 of the OCaml manual. It's listed specifically as a language extension.

like image 181
Jeffrey Scofield Avatar answered Mar 12 '26 10:03

Jeffrey Scofield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!