OCAML how to find the next element of a variant

I have → type week = MON | TUE | WED ...... I want to create a function tomorrow, which will return the next day! For example, if I call MON tomorrow, the function will return TUE.

+4
source share
2 answers

There is no built-in language construct that allows you to do this. Therefore, you must write the function yourself:

let tomorrow = function | MON -> TUE | TUE -> WED ... 

Another possibility is to implement these functions:

 val int_of_week: week -> int val week_of_int: int -> week 

It happens that these functions are trivial to write with Obj.magic. They will allow you to implement tomorrow as:

 let tomorrow w = week_of_int ((int_of_week w + 1) mod 7) 

which is probably closer to what you had in mind.

But this solution is less secure:

  • tomorrow's function assumes that int_of_week MON = 0, int_of_week TUE = 1, etc .;
  • You need to document week_of_int behavior for integers that are not between 0 and 6;
  • and, just as importantly, Obj.magic is not really part of the language.
+5
source

Unlike Haskell, you cannot just do deriving(Ord) and call succ / pred You will pass these functions manually. for instance

 let tomorrow = function | MON -> TUE | TUE -> WED | (* etc.. *) 
+1
source

All Articles