Update record field value


I have following record:

type node_t = Element of element_t | Text of text_t

and element_t = {
tag_name: string
children: node_t list;
mutable deleted: bool

and text_t = {
text: string;
line_number: int;

Now, I have a XML node stored in a variable called xml_node
And the data is :

xml_node = Element {tag_name = "cell"; children: []; deleted = false}

I want to update the deleted flag as “deleted=true” in the above node record.

Could you please tell me how to do it?

Thank you in advance

You need to access the element_t payload of the Element constructor in order to modify one of its fields. You can use pattern matching to do that, e.g

(* [set_deleted t x] sets [e.deleted] to [x] if [t = Element e]. *)
let set_deleted t x =
  match t with
  | Element e -> e.deleted <- x
  | Text _ -> ()

Best wishes,

But “e” in your example is type of node_t whereas “deleted” is a type of element_t.

OK, got it.
I just used your solution like below:

match xml_tree with 
        | Element (_ as e) -> 
          e.deleted <- true;
        | _ -> ()

It worked.
Thank you Nicolás.

Note that _ as e is equivalent to writing just e.

Best wishes,

OK Nicolás.
Thanks for the information.

Out of curiosity, any reason why this field is mutable? It is typical in OCaml to use immutable fields and update records with the immutable update syntax (returns a copy of the record with the given changes).

I am not aware of such syntax.
Could you please tell me the syntax?

type example_record = {a : int; b : string};;

let one = { a = 12; b = "hello"};;

let two = { one with b = "world"};;