Sanghyun Kim
Sanghyun Kim

Reputation: 186

ReasonML way of returning various types from a single switch statement

I have predefined types that goes,

type objA = {name: string}
type objB = {age: int}

and I want to have a variant type that goes,

type test = 
| Atype(objA)
| Btype(objB)

and ultimately use pattern-matching to properly return the values of what each type is encompassing.

let testVariant = {name: "helloworld"}
switch(testVariant: test){
| Atype(v) => v
| Btype(v) => v
}

But since the variant values inside Atype and Btype are different, this is not possible. My question is, how do I return some data with different types conditionally using pattern matching.

Upvotes: 0

Views: 123

Answers (1)

Shubham
Shubham

Reputation: 372

You can achieve this by using GADT (To get a better understand read this Sketch).

type objA = {name: string};
type objB = {age: int};

type test('a) =
  | Atype(objA): test(string)
  | Btype(objB): test(int);

let testVariant: type a. test(a) => a = {
  fun 
  | Atype(v) => v.name
  | Btype(v) => v.age
};

Upvotes: 2

Related Questions