I have defined some complex data types, for instance:
type drawer =
{ ...
box: boxes list }
type table =
{ ...
drawers: drawer list }
type room =
{ ...
tables: table list }
And I want to define some functions of similar purposes but with different types of arguments, for exemple:
val compare_size_rooms: room -> room -> bool (* true: bigger, false: smaller *)
val compare_size_tables: table -> table -> bool
val compare_size_boxes: box -> box -> bool
One thing is that sometimes, due to different structures, 2 rooms/tables/boxes may be not comparable, therefore I hope the comparison could give me some extra information, besides just true or false.
My question is, whether it is a common way to define a type info:
type info =
| Incomparable_Tables_One_foldable_Another_non_foldable
| Incomparable_Tables_One_rectangle_Another_triangle
| Incomparable_Boxes_One_in_paper_Another_in_metal
| ...
And I make the functions as following:
val compare_size_rooms: room -> room -> bool * info (* true: bigger, false: smaller *)
val compare_size_tables: table -> table -> bool * info
val compare_size_boxes: box -> box -> bool * info
So that in those functions, I analyse 2 values, if they are comparable, the bool returns which is bigger or smaller, otherwise, info returns useful information of analysis.
This structure seems me not very common, could anyone tell me if it is usual, or to realize the same thing if there is a better way?
Thank you very much
If the two objects you are comparing are not comparable, it is not advisable to return a boolean value as if they were comparable. Instead, you can raise an exception:
The alternative is to use a variant return type which can be either a boolean (when the objects are comparable) or an information type (when they are not). For instance, using the Batteries library:
In the latter case, you will have to
matchwhether the result wasBad infoorOk boolean.