Static String Conversion Function in F #

I am trying to create a function in F # that converts some types to string, but not others. The goal is so that the primitive can be transmitted, but a complex object cannot be transferred by accident. Here is what I still have:

type Conversions =
    static member Convert (value:int) =
        value.ToString()
    static member Convert (value:bool) =
        value.ToString()

let inline convHelper< ^t, ^v when ^t : (static member Convert : ^v -> string) > (value:^v) =
    ( ^t : (static member Convert : ^v -> string) (value))

let inline conv (value:^v) = convHelper<Conversions, ^v>(value)

Unfortunately, my function convgets the following compile time error:

A unique overload for method 'Convert' could not be determined based on type information
prior to this program point. A type annotation may be needed. Candidates: 
    static member Conversions.Convert : value:bool -> string, 
    static member Conversions.Convert : value:int -> string

What am I doing wrong?

+3
source share
3 answers

It works:

type Conversions = Conversions with 
    static member ($) (Conversions, value: int) = value.ToString()
    static member ($) (Conversions, value: bool) = value.ToString()

let inline conv value = Conversions $ value

conv 1 |> ignore
conv true |> ignore
conv "foo" |> ignore //won't compile
+6
source

For some reason, it seems that use is (^t or ^v)in limitation, and not only ^vmakes it work.

type Conversions =
    static member Convert (value:int) =
        value.ToString()
    static member Convert (value:bool) =
        value.ToString()

let inline convHelper< ^t, ^v when (^t or ^v) : (static member Convert : ^v -> string)> value =
    ( (^t or ^v) : (static member Convert : ^v -> string) (value))

let inline conv value = convHelper<Conversions, _>(value)

, , , Convert , - .

+4

Well, Daniel answered. Here is what I wanted at the end:

type Conversions = Conversions with
    static member ($) (c:Conversions, value:#IConvertible) =
        value.ToString()
    static member ($) (c:Conversions, value:#IConvertible option) =
        match value with
        | Some x -> x.ToString()
        | None -> ""

let inline conv value = Conversions $ value

An interface type IConvertibleis just a convenient way to capture all the primitives.

This leads to the following behavior (FSI):

conv 1         // Produces "1"
conv (Some 1)  // Produces "1"
conv None      // Produces ""
conv obj()     // Compiler error
+2
source

All Articles