How to switch the type of an item in my type signature?

65 Views Asked by At

I'm sorry if my vernacular is wrong here. I'm very new to coding.

I have created two records. I want my program to take in these two records. However, in the type signature both of the items are classified as the second record. I'm not sure how heavily this is impacting the program, but it's beginning to throw more errors due to this problem.

I've tried changing the orders around but I've never encountered a problem like this so I'm kind of at a loss. Is there a way to manually put in what I want the types of the type signature to be?

type lecture = {
  lecture: string,
  day: string,
  time: list(int),
  priority: int,
};

type workweek = {
  day: string,
  time: list(int),
  priority: int,
};

let schedSorter = (lecture, workweek) =>
  if (lecture.time == workweek.time) {
    switch (lecture.priority, workweek.priority)
1

There are 1 best solutions below

0
octachron On

When using two record types with common field names, one may need to help the typechecker to disambiguate between the two types.

For instance, consider this line:

lecture.priority, workweek.priority

It is impossible to look at this line and deduce that lecture ought to have type lecture while workweek has type workweek without some more information. And type inference is always local. In such ambiguous situation, the typechecker always pick the last defned types as the default option.

It is possible to avoid this ambiguous choice in a few ways.

  • First, we can add an explicit type annotation:
let schedSorter = (lecture:lecture, workweek:workweek) =>
  • Another option is to define the two types in their own modules:
module Lecture = {
  type t = {
    lecture: string,
    day: string,
    time: list(int),
    priority: int,
  };
}

module Workweek = {
  type t = {
    day: string,
    time: list(int),
    priority: int,
  };
};

With this definition, we are now able to distinguish the field Lecture.priority from the field Workweek.priority. Thus, the ambiguous line

lecture.priority, workweek.priority

can be clarified as

lecture.Lecture.priority, workweek.Workweek.priority
  • Lastly, in your case, it seems like the lecture type contains a workweek, thus it might work to rewrite the lecture type as
type lecture = {
  lecture: string,
  workweek: workweek
};

which completely avoids the ambiguity of duplicated field names.