Search code examples
ocamlrecord

Update a single record field in an anonymous record in OCaml


This is not valid syntax, but is there something similar that can be done to get a new updated anonymous record, similar as using with with normal records?

type user = User {id: int, ... more fields}
let u = User {id = 1, ...}
let u2 = User with id = 2

Solution

  • If you're asking how you can access the entirety of the record from a constructor, you can do this with pattern-matching.

    # type user = User of { id : int; name : string };;
    type user = User of { id : int; name : string; }
    # let u = User { id=1; name="foo" };;
    val u : user = User {id = 1; name = "foo"}
    # let u2 = 
        let User r = u in
        User { r with id=2 };;
    val u2 : user = User {id = 2; name = "foo"}
    

    You can also employ as to bind a name to part of the record while binding r to the entire record.

    # let u3 = 
        let User ({id; _} as r) = u2 in
        User { r with id=id+1 };;
    val u3 : user = User {id = 3; name = "foo"}
    

    Since User {id; _} as r would bind r to the entire pattern, parentheses are needed to limit r to just the record portion of the pattern.