Define a type that is the set of all the strings of Len n


#1

There is a way in ocaml to define a type X that is the set of all the strings of Len n?

For instance:
type String6 = ... ;;

Iā€™m also wondering if that is something to that should be statically checked or dynamically checked, because it seems that other statically checked language for instance js + flow are not expressive enough to do that.

Ty :slight_smile:


#2

Here is something to get you started. Any value of type String6.t is guaranteed to be of length 6.

module String6 : sig
  type t
  val of_string : string -> t option
  val to_string : t -> string
end = struct
  type t = string

  let of_string s =
    let len = String.length s in
    if len = 6 then Some s else None

  let to_string s = s
end

#3

After that you are possibly looking at a functor, which will generate a module for any len.