I often want to apply a function to the values inside some variant, so that the result of the function has the same type as the input. How can I make the types work out? Here's my current attempt:
module T : sig
type generic =
[ `Foo of int
| `Bar of int ]
val map : (int -> int) -> ([< generic] as 'a) -> 'a
(* val a : [`Foo of int] *)
end = struct
type generic =
[ `Foo of int
| `Bar of int ]
let map fn = function
| `Foo x -> `Foo (fn x)
| `Bar x -> `Bar (fn x)
let map : (int -> int) -> ([< generic] as 'a) -> 'a = Obj.magic map
(*
let a : [`Foo of int] = `Foo 1 |> map succ
let b : [`Bar of int] = `Bar 1 |> map succ
*)
end
This works as-is, but if I uncomment the let a
line then I get:
Values do not match:
val map : (int -> int) -> [ `Foo of int ] -> [ `Foo of int ]
is not included in
val map : (int -> int) -> ([< generic ] as 'a) -> 'a
It seems like defining a
has changed the type of map
, which seems odd.
On the other hand, putting this after the end of the module works:
open T
let a : [`Foo of int] = `Foo 1 |> map succ
let b : [`Bar of int] = `Bar 1 |> map succ
Finally, if I change the definition of map
to:
let map : 'a. (int -> int) -> ([< generic] as 'a) -> 'a = Obj.magic map
(i.e. just adding an explicit 'a.
to the start) then it complains:
Error: This definition has type (int -> int) -> ([< generic ] as 'a) -> 'a
which is less general than
'b. (int -> int) -> ([< generic ] as 'b) -> 'b
Can someone explain what's going on? Is there a better way to do this? I can use a GADT to avoid the Obj.magic
, but then I have to pass it to every function call, which I'd like to avoid.
Note about the real system
In my actual program, I have various node types (Area
, Project
, Action
, Contact
, etc) and different operations apply to different types, but some are common.
For example, with_name
can rename any node type, but if I rename an Action
then the result must be another action. If I rename an [Area | Project | Action]
then the result must be an [Area | Project | Action]
, etc.
I originally used a tuple, with the common details outside (e.g. (name * Action ...)
) but this makes it hard for users to match on the different types (especially as they're abstract) and some features are common to subsets (e.g. only Project
s and Action
s can be starred).