types - OCAML how to find the next element of the variant -


i have -> type week = mon | tue | wed...... want create function tomorrow return next day! example , if call "tomorrow mon", function return tue.

there no built-in language construction allows this. should write function yourself:

let tomorrow = function   | mon -> tue   | tue -> wed   ... 

another possibility implement these functions:

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

it happens functions trivial write obj.magic. allow implement tomorrow as:

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

which closer had in mind.

but solution less safe:

  • function tomorrow assumes int_of_week mon = 0, int_of_week tue = 1 , on;
  • you need document behavior of week_of_int integers not between 0 , 6;
  • and, last not least, obj.magic not part of language.

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -