Ehsan Ghanbari

Experience, DotNet, Solutions

Using Generic type for type casting in F#

In order to validate some input of type object into numeric types, you can use System.Convert in F#. 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

 

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns. I'm spending a lot of my time on software architecture. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
using Log4net in asp.net MVC4
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?
comments powered by Disqus