Elegant way to update field of a record in a hashtbl

Hi, I have a custom records as below

module IntSet = Set.Make(Int)
type block = {
    pred: IntSet.t
    succ: IntSet.t
}

and I create a Hashtbl to store the relationship between block_number and block

let blocks = Hashtbl.create (module Int) in 
let blk = {
    pred = IntSet.of_list [1,2]
   ;succ = IntSet.of_list [3,4] 
} in
Hashtbl.set blocks ~key:0 ~data:blk

I understand that I can create a new block based on blk with new pred or succ and then reassign to Hashtbl blocks with key = 0.

let blk = {
    pred = IntSet.of_list [1,2]
   ;succ = IntSet.of_list [3,4] 
} in
let () = Hashtbl.set blocks ~key:0 ~data:blk in
let blk_new = {
    pred = blk.pred
   ;succ = IntSet.of_list [0]
} in
Hashtbl.set blocks ~key:0 ~data:blk_new

However, considering there may be many other fields in my real records, it seems tedious to rewrite all other fields again except the updated one.

So my question is: Is there any elegant way to update record field in a hash table?

Thank you in advance :slight_smile:

Your problem can be solved using standard record update syntax. In your case it would be:

let blk_new = { blk with succ = IntSet.of_list [0] }
4 Likes

ohhhhhh, that’s great, cheers!

Is it Janest core? Looks non-standard.