Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit type parameters in let bindings in classes

Tags:

.net

generics

f#

When I try to create some class like

type MyType () =
    let func<'T> () = ()

The compiler says that there's an error:

Explicit type parameters may only be used on module or member bindings

But the MSDN says:

A let binding at the module level, in a type, or in a computation expression can have explicit type parameters. A let binding in an expression, such as within a function definition, cannot have type parameters.

Why documentation and compiler say different things?

like image 400
Dmitrii Lobanov Avatar asked Nov 15 '12 11:11

Dmitrii Lobanov


1 Answers

This appears to be a syntactic restriction on let bindings inside a class. However, you can still define a generic local function, you just have to specify the type parameters in type annotations:

type MyType () =
   let func (x : 'T) : 'T = x

I do not think this is explicitly syntactically forbidden by the specification, because the specification says that a class definition has the following structure:

type type-name patopt as-defnopt =
      class-inherits-declopt
      class-function-or-value-defnsopt
      type-defn-elements

and class-or-value-defn is defined as:

class-function-or-value-defn := attributesoptstaticoptlet recopt function-or-value-defns

where function-or-value-defns may be a function definition with explicit type parameters:

function-defn :=
inlineoptaccessopt ident-or-op typar-defnsopt argument-pats return-typeopt = expr

like image 103
Tomas Petricek Avatar answered Sep 28 '22 07:09

Tomas Petricek