2 people like it.

Not dependent types...

Sometimes you have a type safe method you need to wrap inside a generic (type/method). Here's an easy but nasty way of doing it

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
open System
let doesNotWorkRead<'a> str : 'a option =
    match typeof<'a> with
    | t when t = typeof<int> ->
        Int32.Parse str |> Some
    | t when t = typeof<string> ->
        Some str
    | _ -> None

let read<'a> str : 'a =
    match typeof<'a> with
    | t when t = typeof<int> ->
        Int32.Parse str |> box |> unbox<'a>
    | t when t = typeof<string> ->
        str |> box |> unbox<'a>
    | _ -> failwith "The programmers proof engine failed"
namespace System
val doesNotWorkRead : str:string -> 'a option

Full name: Script.doesNotWorkRead
val str : string
type 'T option = Option<'T>

Full name: Microsoft.FSharp.Core.option<_>
val typeof<'T> : Type

Full name: Microsoft.FSharp.Core.Operators.typeof
val t : Type
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
type Int32 =
  struct
    member CompareTo : value:obj -> int + 1 overload
    member Equals : obj:obj -> bool + 1 overload
    member GetHashCode : unit -> int
    member GetTypeCode : unit -> TypeCode
    member ToString : unit -> string + 3 overloads
    static val MaxValue : int
    static val MinValue : int
    static member Parse : s:string -> int + 3 overloads
    static member TryParse : s:string * result:int -> bool + 1 overload
  end

Full name: System.Int32
Int32.Parse(s: string) : int
Int32.Parse(s: string, provider: IFormatProvider) : int
Int32.Parse(s: string, style: Globalization.NumberStyles) : int
Int32.Parse(s: string, style: Globalization.NumberStyles, provider: IFormatProvider) : int
union case Option.Some: Value: 'T -> Option<'T>
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = String

Full name: Microsoft.FSharp.Core.string
union case Option.None: Option<'T>
val read : str:string -> 'a

Full name: Script.read
val box : value:'T -> obj

Full name: Microsoft.FSharp.Core.Operators.box
val unbox : value:obj -> 'T

Full name: Microsoft.FSharp.Core.Operators.unbox
val failwith : message:string -> 'T

Full name: Microsoft.FSharp.Core.Operators.failwith
Raw view Test code New version

More information

Link:http://fssnip.net/sN
Posted:9 years ago
Author:mavnn
Tags: playing with types