user2249250
user2249250

Reputation: 41

OCAML how to find the next element of the variant

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

Upvotes: 4

Views: 297

Answers (2)

Bardou
Bardou

Reputation: 446

There is no built-in language construction which allows you to do this. So you should 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 those functions are trivial to write with Obj.magic. They would 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 safe:

  • function tomorrow assumes that int_of_week MON = 0, int_of_week TUE = 1 and so on;
  • you need to document the behavior of week_of_int for integers which are not between 0 and 6;
  • and, last but not least, Obj.magic is not actually part of the language.

Upvotes: 5

rgrinberg
rgrinberg

Reputation: 9878

Unlike in Haskell, you cannot just do deriving(Ord) and call succ/pred You will haveto code these functions by hand. For example

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

Upvotes: 1

Related Questions