views:

64

answers:

1

I'm trying to write a polymorphic function, which needs to do something slightly different depending on the type of the parameter. Is there any way that I can do a pattern match on the type of the object, using the builtin types? I'm thinking of something along these lines:

let to_string v =
    match v with
    | string -> v
    | int -> string_of_int v
    | _ -> ""

but this doesn't seem to be a valid OCaml program.

I have seen this question, but that doesn't quite answer my question either. I would prefer to use the standard,builtin types rather than constructing new types for this (although I can do that if that is the only way).

+2  A: 

Actually that answer completely applies to you. You can only match one type class, and the type defined by the union of int, string, float, ... does not exist, and needs to be created (as in the previous answer). 'a operates on a particular type, but does not represent a union of all types.

You might be able to do what you want using an external C function (18.3), although, glancing at the atomic tags section, I'm not sure you'll be able to differentiate char and int.

nlucaroni
:( - that's what I was afraid of. Oh well, I guess my program will just not quite look as nice.
a_m0d
Why are you trying to do something like this? there probably is a better way.
nlucaroni
I thought that I would be able to write a polymorphic function this way, with overrides for the different types that I need, but thinking it over some more, I will probably need to use variants anyway, since I will end up making a lexing step as well.
a_m0d