I do not understand why the following code does not compile
module GenericsTest =
open System
type Dog = {
name:string
}
type Apple = {
size:int
}
let get<'a> (id:string) =
Activator.CreateInstance<'a>()
let creatorInferred getAsParam =
let apple = {
name = getAsParam "some-apple"
}
let dog = {
size = getAsParam "some-dog"
}
(apple, dog)
let creatorWithTypeAnnotation (getAsParam:string->'a) =
let apple = {
name = getAsParam "some-apple"
}
let dog = {
size = getAsParam "some-dog"
}
(apple, dog)
If you look at the 2 "creator..." function - both of them give the compile error..
this expression was expected to have the type int... but here has the type string
I can see that F# is infering the return type of the getAsParam method to be int, because it is the first one that it encounters. However, why does it not then decide to use a generic return type?
As you can see, i have tried to for the function signature in the creatorWithTypeAnnotation method - but this has no affect.
I'm stumped! How do i force this to recognise that the getAsParam function should return a generic?
Apple) the type-inference will specializegetAsParamintostring -> Apple, so of course your second usage of it (for theDog) must fail - you could even see it if you remove the part with the error - the compiler should warn you that it constrained'aintoApple- just try to think how you would write a function returning a real generic'awithout cheating (reflection, defaults, ...) - Random DevgetAsParam- Random Dev'ain yourgetAsParamas an generic parameter tocreateorWithAnnotation- see why it will not can be two different things here? - so if you need two different results you have to use two differentgetAsParam1andgetAsParam2arguments too - Random Dev