Blog

Filter posts by Category Or Tag of the Blog section!

Using Generic type for type casting in F#

Thursday, 19 October 2017

In order to validate some input of type object into numeric types, you can use System.Convert in C#. We have them in F# as well! Look at the following function:

 

open System

let validate<'a, 'b> (cast: 'a -> 'b) (x: 'a) =
    try
        cast x |> Some
    with _ -> None

let a = validate int "3423"
let d = validate<obj, decimal> Convert.ToDecimal (null :> obj)
let e = validate<string, DateTime> Convert.ToDateTime "2017-10-10"

 

Validate has been used to convert obj to decimal and even to DateTime. In order to see the result of the following piece of code, you can use it in F#.Net Core console application: 

 

[<EntryPoint>]

let main argv =

    printfn "%A" e // or d and a that has calculated by Validate<,>

    0

 

Category: Software

Tags: F#

comments powered by Disqus