2

Consider the following:

type Foo(bar:'a -> 'a list) =
  member __.Bar = bar

I get a warning on the first 'a in the parameter list saying:

This construct causes code to be less generic than indicated by the type annotations. The type variable 'a has been constrained to be type 'obj'.

Why do I get this warning?

In this specific example, is it possible to have a member that converts a value of an arbitrary type to a list of such types and have that member supplied through the constructor? (One could for example imagine Foo being instantiated with List.replicate x for any integer x that the user chooses.)

I don't want to make Foo itself generic, because I have many such parameters and members.

(The reason I'm trying this is that I want some kind of structure that, among other things, contains user-overridable generic functions.)

cmeeren
  • 3,890
  • 2
  • 20
  • 50

1 Answers1

3

Even if you make Foo generic, you don't need to explicitly provide the generic parameters when calling it if they can be inferred:

type Foo<'a>(bar:'a -> 'a list) =
    member __.Bar = bar

Foo(fun x -> [x + 1])

I'm not sure if that helps you but in general "Functions lose genericity when passed as values".

TheQuickBrownFox
  • 10,544
  • 1
  • 22
  • 35