Passing a type into a function

Is there any way to pass a type into a function?

The purpose would be to push marshalling code into a send function, rather than obstructing the main code.

I’m currently doing something like:

type 'a typ = Int: int typ | Bool : bool typ

send_typed : 'a -> 'a typ -> unit 
  = fun v typ ->
  let s = match typ with 
    | Int -> Int.to_string v 
    | Bool -> Bool.to_string v
  in send s 

However if I could match on the type explicitly that would be easier.

(The reason that this is required is due to using protocol buffers, which requires a bytes type and sending via something which only takes strings… hence: v |> Protobuf.Encoder.encode_exn protobuf_from_v |> Bytes.to_string…)

What we do for sending and receiving Protobuf is passing in the encoder and decoder functions along with the callback that will receive the generated protobuf type and return a generated protobuf type. Works pretty well and doesn’t require first-class types (types don’t exist at runtime, so you can’t really “pass” anything).

1 Like

I was expecting this answer tbh, I was just hoping that there was some kind of compiler magic which could help here (where internally you are calling a specialised function one per argument type)…