F # dynamic option

I need to indicate that my member property will return something like dynamic?in C #. Is it possible to use a dynamic data type in F #?

type Data =
    | Text of string
    | Number of string
    | Date of string
    with

    member x.Value
        with get() : dynamic option = 
            match x with
            | Text(value) ->
                if value.Length > 0 then Some(value) else None
            | Number(value) ->
                let (success, number) = Decimal.TryParse value
                if (success) then Some(number) else None
            | Date(value) ->
                let (success, date) = DateTime.TryParse value
                if (success) then Some(date) else None

This code cannot be compiled, since the return type is determined as string optionfrom a text field. Keyword dynamicunknown in F #. Any ideas?

+3
source share
1 answer

Try to make this data type:

type ThreeWay = S of string | N of Decimal | D of DateTime

or use type System.Object:

open System
type Data =
    | Text of string
    | Number of string
    | Date of string
    with

    member x.Value
        with get() : Object option = 
            match x with
            | Text(value) ->
                if value.Length > 0 then Some(value :> Object) else None
            | Number(value) ->
                let (success, number) = Decimal.TryParse value
                if (success) then Some(number :> Object) else None
            | Date(value) ->
                let (success, date) = DateTime.TryParse value
                if (success) then Some(date :> Object) else None

To get the value:

let d = Number("123")
let v = d.Value
match v with
| Some(x) -> x :?> Decimal // <-- TYPE CAST HERE
+2
source

Source: https://habr.com/ru/post/1771095/


All Articles