Proper way of ReasonML record pattern-matching

81 Views Asked by At

I have a record type that goes,

type person = {
 name: string,
 gender: string,
 age: int
}

and have lots of records that fit with the type. What I want to do is to extract only [name, age] from the person and make a new record. To do so, I initially thought of using a pattern-matching technique that goes like,

switch(input) {
  |({name, _, gender} => //make a new record by extracting only name and age
  |_ => ();
}

Does this approach make sense? If so, how should I go about it? If not, what would be the proper way of deleting a key from a record(records are immutable, so this doesn't really make sense), or extracting another record from an existing one?

1

There are 1 best solutions below

0
On BEST ANSWER

You actually don't need a switch to pattern-match.

Basically, just using let {name, gender, age: _} = input is enough to extract the two attributes you want.

Your could make a helper function like this:

type person = {
  name: string,
  gender: string,
  age: int,
};

type nameAndGender = {
  name: string,
  gender: string,
};

let personToNameAndGender = (person) => {
  let {name, gender, age: _} = person;
  {name, gender};
};

Keep in mind that you need to define both record types beforehand.

NOTE: You can also omit the age if you just match on the partial record

let {name, gender}: person = person;

but then you need to annotate it since the type system cannot figure out automatically which of the two records it is.

Here is a working example.