Type of restricted string values

As soon as we start the journey in F #, is it possible to define a type that is limited to a specific set of string values? F.ex. it can only represent values "Foo", "Bar"and "Baz"trying to assign it any other value will result in an error or even better failure during compilation.

UPDATE: So far, I have been thinking of creating a type that is a string, and using the create function:

type Constrained = string
let createConstrained (constrained : Constrained) = 
    match constrained with
        | "foo" -> constrained
        | "bar" -> constrained
        | "baz" -> constrained
        | _ -> failwith "Can be only foo, bar or baz"

Then I thought about using DU and some kind of function that returns a string based on an option (is this the correct name for it?):

type Constrained = FOO | BAR | BAZ
let constrainedString constrained =
    match constrained with
        | FOO -> "foo"
        | BAR -> "bar"
        | BAZ -> "baz"
        | _ -> failwith "Can only be foo, bar or baz"

Not sure if any of them is the way to go.

+4
source share
1 answer

, , , , F # , ; .

, , ToString:

type Constrained =
    Foo | Bar | Baz
    override this.ToString () =
        match this with
        | Foo -> "Foo"
        | Bar -> "Bar"
        | Baz -> "Baz"

Constrained , string:

> string Foo;;
val it : string = "Foo"
> string Baz;;
val it : string = "Baz"

, , "%A" sprintf:

type Constrained =
    Foo | Bar | Baz
    override this.ToString () = sprintf "%A" this

"%A" , , . , .

+4

All Articles