1

There is a way to have a specific implementation of a function in C++ based on the type of the argument. Is there anything similar to this in F#?

Trident D'Gao
  • 18,973
  • 19
  • 95
  • 159
  • possible duplicate of [F# functions with generic parameter types](http://stackoverflow.com/questions/501069/f-functions-with-generic-parameter-types) – John Palmer Sep 28 '13 at 03:57
  • Looks like a duplicate. Don't understand why someone felt it necessary to down-vote though. Be polite please people when duplicates appear. – David Arno Sep 28 '13 at 12:01
  • I don't think it's a duplicate. It's closely related to that question, but technically speaking function specialization is harder to get it working than the case presented in that question. – Gus Sep 29 '13 at 08:43
  • @Gustavo, I agree, specializations aren't overloads. – Trident D'Gao Sep 29 '13 at 09:59

1 Answers1

5

The short answer is NO, the reasons are explained in the question John linked.

It will work with method overloads though this is more a .NET feature than F# specific.

type T = T with
    static member test (x:'a   list) = "Generic version"  
    static member test (x:int  list) = "Specialized for int"  
    static member test (x:char list) = "Specialized for char"  

> T.test ["0"] ;;
val it : string = "Generic version"
> T.test [0] ;;
val it : string = "Specialized for int"

But with functions there is no clean way to do this, you can find some tricks like:

type T = T with
    static member ($) (a:T, x:'a   list) = "Generic version"  
    static member ($) (a:T, x:int  list) = "Specialized for int"  
    static member ($) (a:T, x:char list) = "Specialized for char"  

let inline f a = T $ a : string

> f ["0"] ;;
val it : string = "Generic version"
> f [0] ;;
val it : string = "Specialized for int"

But this is very limited, it creates an inline function with static constraints which at the current version of F# are not always able to reflect the same overload resolution thus I don't think you can go far with this approach.

Gus
  • 25,839
  • 2
  • 51
  • 76
  • There are two neat Haskell typeclass emulations based on this trick: http://code.google.com/p/fsharp-typeclasses and https://github.com/gmpl/FsControl. – Eugene Fotin Sep 28 '13 at 22:46