Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Riddle: how to call an overload of a method?

First part: call F# from F#

Let's say we have the following type defined in F#:

type MyClass =
    static member Overload1 (x, y) = "Pim"
    static member Overload1 (x : System.Tuple<_, _>) = "Pam"
    static member Overload1 x = "Pum"

You are now in another module (in another file).

How can you call each of the three methods shown above?

Second part: call C# from F#

Now, you define a class in C#:

public class MyClass {
    public static string Overload1<a, b>(a x, b y) { return "Pim"; }
    public static string Overload1<a, b>(Tuple<a, b> x) { return "Pam"; }
    public static string Overload1<a>(a x) { return "Pum"; }
}

From a F# code, how can you call each of the three methods now defined in C#?

like image 651
Bruno Reis Avatar asked Jan 23 '23 19:01

Bruno Reis


2 Answers

Hmm, I am unclear if it is possible to call the F# "Pam" method. But here's the rest.

C#:

using System;
namespace CSharp
{
    public class MyClass
    {
        public static string Overload1<a, b>(a x, b y) { return "Pim"; }
        public static string Overload1<a, b>(Tuple<a, b> x) { return "Pam"; }
        public static string Overload1<a>(a x) { return "Pum"; }
    }
}

F#:

namespace FSharp

type MyClass =
    static member Overload1 (x, y) = "Pim"
    static member Overload1 (x : System.Tuple<_, _>) = "Pam"
    static member Overload1 x = "Pum"

namespace DoIt

module Examples =
    let CallFSharp() =
        printfn "%s" <| FSharp.MyClass.Overload1(1,2)   // Pim
        printfn "%s" <| FSharp.MyClass.Overload1((1,2)) // Pum!
        printfn "%s" <| FSharp.MyClass.Overload1(())    // Pum


    let CallCSharp() =
        printfn "%s" <| CSharp.MyClass.Overload1(1,2)             // Pim
        printfn "%s" <| CSharp.MyClass.Overload1<int,int>((1,2))  // Pam
        printfn "%s" <| CSharp.MyClass.Overload1(())              // Pum

    do
        CallFSharp()        
        CallCSharp()        

Of course, in practice it will be rare to see methods in IL that take System.Tuple<...> objects as parameters.

like image 156
Brian Avatar answered Jan 30 '23 17:01

Brian


Here's an answer to the F# part:

MyClass.Overload1(1,2)
MyClass.Overload1<_,_>(unbox (box (1,2)) : System.Tuple<int,int>)
MyClass.Overload1 1
like image 43
kvb Avatar answered Jan 30 '23 18:01

kvb