Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce explicit type arguments

Tags:

inline

f#

I have a generic function where it's easy to get the compiler to infer the wrong type parameters. The type parameters only control the return type, and if I accidentally miss off a type annotation, the compiler infers obj.

How can I make it a compile-time error to call my function without giving it explicit type parameters? The Unchecked.defaultof function works the way I'd like:

> Unchecked.defaultof;;

  Unchecked.defaultof;;
  ^^^^^^^^^^^^^^^^^^^

stdin(1,1): error FS0685: The generic function 'defaultof' must be given explicit type argument(s)
like image 921
Tim Robinson Avatar asked May 18 '11 09:05

Tim Robinson


2 Answers

The defaultof function uses a special attribute. The F# source code is, once again, useful. The implementation of the function is in prim-types.fs, but the attribute is added in the interface file prim-types.fsi. A combined declaration would be:

[<RequiresExplicitTypeArguments>] 
let inline unsafeDefault<'T> : 'T = (# "ilzero !0" type ('T) : 'T #)

The inline IL (# ... #) is limited to F# core, but the declaration is something anybody can use.

You can find the attribute in section 16 (page 217) of the F# specification:

When applied to an F# function or method, indicates that the function or method must be given explicit type arguments when used. For example, typeof<int>. This attribute should be used only in F# assemblies.

like image 169
Tomas Petricek Avatar answered Nov 02 '22 12:11

Tomas Petricek


RequiresExplicitTypeArgumentsAttribute should help

like image 7
desco Avatar answered Nov 02 '22 14:11

desco