2

I've been trying to learn F# lately and coming from object-oriented background, I have a little problems understanding generics in this one case.

Let's say I have the following functions:

let genericFunction<'a> (x: 'a) =
    ()

let myFunction (fn: ('a -> unit)) =
    fn 2
    fn 2UL

let test =
    myFunction genericFunction

As a C# developer I'd expect fn to be a generic function, which can take any argument. But the fn 2 call constraints the generic parameter 'a to int and thus it cannot be called with uint64.

Why the generic type is constrained? How one would implement this without passing in two functions?

The compiler warns about the constraining and finally errors:

source_file.fs(5,8): warning FS0064: This construct causes code to be less generic than indicated by the type annotations. The type variable 'a has been constrained to be type 'int'.

source_file.fs(6,8): error FS0001: This expression was expected to have type
    int    
but here has type
    uint64    

Here's the error: http://rextester.com/RRRWTR28520

Jani
  • 1,088
  • 1
  • 10
  • 18
  • 3
    Check out this answer: https://stackoverflow.com/a/45567508/180286 – Fyodor Soikin Sep 15 '17 at 19:39
  • Thanks! Good answer, exactly what I was looking for, but with wrong search terms. – Jani Sep 15 '17 at 19:54
  • 1
    @jani Have a look at this answer as well, which is older and has another approach plus some more information about the problem: https://stackoverflow.com/questions/7213599/generic-higher-order-function/7224269#7224269 – Gus Sep 16 '17 at 07:32
  • @Gustavo Thanks for the link. I have to take another look at the magic tomorrow with fresh eyes. Sadly the link to the gist (n-uples) in your answer is dead, any chance reviving it? – Jani Sep 16 '17 at 20:56
  • @Jani I fixed the broken link. – Gus Sep 17 '17 at 10:53

0 Answers0