How to create a type whose value can only be in the valid range?

How to create a type whose value can only be in the valid range?

Most statically typed languages ​​provide numeric types in which each type supports a range of values.

int is an example of this type.

To support the following:

Make illegal states unpredictable

How to create a type so that assigning a value out of range leads to an error at compile time?

For example: Type PositiveInteger // range from 0 to 2 147 483 647

UPDATE

I tried to do this:

type PositiveInteger = private PInt of int with
    static member FromInt i =
       if i <= 0 then failwith "out of range" else PInt i

let isSuccessful = 
    PInt -1

However, the above code compiles when I want it to select “out of range” at compile time. Is it fair to say that this is not supported for compile time?

+4
1

( p <= > p > 0)

(, peano, ):

type PositiveInteger =
   | One
   | Succ of PositiveInteger

, :

let one = One
let two = Succ one
...
let rec add a b =
     match (a,b) with
     | (One, b)    -> Succ b
     | (Succ a, b) -> Succ (add a b)

( ... )


, , - :

type PositiveInteger = private PInt of int with
    static member FromInt i =
       if i <= 0 then failwith "out of range" else PInt i

, with:

type PositiveInteger = 
    private | PInt of int
    static member FromInt i =
        if i <= 0 then failwith "out of range" else PInt i
+6

All Articles