Reputation: 5510
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
Upvotes: 2
Views: 68
Reputation: 24577
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:
exception Incomparable_Tables_One_foldable_Another_non_foldable
let compare_size_tables a b =
if comparable a b then
a.size < b.size (* Or whatever you do *)
else
raise Incomparable_Tables_One_foldable_Another_non_foldable
(* val compare_size_tables : table -> table -> bool *)
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:
open BatPervasives
type info =
| Incomparable_Tables_One_foldable_Another_non_foldable
| ...
let compare_size_tables a b =
if comparable a b then
Ok (a.size < b.size)
else
Bad (Incomparable_Tables_One_foldable_Another_non_foldable)
(* val compare_size_tables : table -> table -> (bool, info) BatStd.result *)
In the latter case, you will have to match
whether the result was Bad info
or Ok boolean
.
Upvotes: 1