Convert polymorphic type to string ('a & # 8594; string)

Given the following type definition:

type 'a range = Full | Range of ('a * 'a);;

How to convert values ​​of this type to strings?

I currently have:

let string_of_range r = match r with
  | Full -> "Full"
  | Range(a,b) -> "Range("^(string_of_int a)^","^(string_of_int b)^")";; 

But, of course, this suggests that a and b are of type int. They can also be floats or characters (see my previous type restriction question)

+3
source share
3 answers

Modify your function to accept a string converter and use it in your implementation. Then, when you call it, go to the appropriate converter and range. Sort of:

let string_of_range str_conv = function
  | Full -> "Full"
  | Range(a, b) -> "Range (" ^ (str_conv a) ^ ", " ^ (str_conv b) ^ ")"

It will be of type: string_of_range : ('a -> string) -> 'a range -> string

Call example:

string_of_range string_of_int (Range (1, 2))

Arranged this way, you can easily create more specialized converters.

let string_of_int_range = string_of_range string_of_int

It will be of type: string_of_int_range : int range -> string

+8
source

, sexplib. , :

type 'a range = Full | Range of ('a * 'a) with sexp

val sexp_of_range : ('a -> Sexp.t) -> 'a range -> Sexp.t

:

type int_range = int range with sexp

val sexp_of_int_range : int range -> Sexp.t

:

let to_string range = Sexp.to_string (<:sexp_of<int range>> range)
+2

How to make your data type as follows:

type 'a range = Full | Range of ('a * 'a * ('a -> string));;
0
source

All Articles