0
votes

I have Some v where v could be an int, bool, or even something like string option * string, how can I check if v is an int, bool, or string option * string?

If this isn't possible then maybe I am approaching my problem wrong.

Depending on what v is, I want to return different types that are of the same polymorphic type, say, type 'value' that I declared.

1
How does your type value look like? What constructors does it have? If its like type 'a value = Val of 'a, you can create e.g. a function let convert_option_to_value = function | Some x -> Val x | None -> failwith "not supported".phimuemue
Otherwise you could have an extra parameter reifying the type of v (e.g. using a GADT).gallais

1 Answers

3
votes

If you want, you can use a GADT:

type _ value =
  Int    : int -> int value
| String : string -> string value
| Bool   : bool -> bool value

let get_value : type v. v value -> v = function
  Int i -> i
| String s -> s
| Bool b -> b

For example:

let _ =
  Printf.printf "%d %s %b\n%!" 
   (get_value (Int 2)) 
   (get_value (String "toto")) 
   (get_value (Bool false))

You can test the code on http://try.ocamlpro.com/ it should work.