Nachmi Kott
Nachmi Kott

Reputation: 39

How to extract information from a record in OCaml

I have a type record:

type record = { first : string; second : string list; third : string }

I want to extract data from it using match...How would I do that?..

Please let me know. Thanks!

Upvotes: 1

Views: 1485

Answers (1)

superkonduktr
superkonduktr

Reputation: 655

You can match the whole record:

match my_record with
| { first = "something"; } -> do_something
| { second = hd :: tl; third = "something else"; } -> do_something_else
(* ... *)

or target specific fields in it with the dot notation:

match my_record.second with
| hd :: tl -> do_something
(* ... *)

It is also possible to destructure a record in a function with a syntactic shortcut called field punning:

let fun_example { first; third; _ } =
  "This is first: " ^ first ^ " and this is third: " ^ third

or by providing aliases for the fields:

let fun_example_2 { first = f; third = t; _ } =
  "This is first: " ^ f ^ " and this is third: " ^ t

The underscore ; _ in the pattern is used to tell the compiler it shouldn't worry about incomplete matches when the #warnings "+9" directive is turned on in the toplevel. It may be omitted depending on your style.

For more intricate details please refer to RWO, there's a great chapter on records!

Upvotes: 7

Related Questions