Home » F# Type Inference

F# Type Inference

by Online Tutorials Library

F# Type Inference

This topic is about how F# compiler infers types of values, functions, variables, parameters and return values.

Type inference means when you are writing code then you don’t need to specify type of values or variables. F# compiler is strong enough to infer the type of value. Omitting F# type information does not mean that F# is a dynamic type language. F# is strongly statically typed language. It means compiler deduces the automatic type during code compilation.

It makes code more readable, less in size and saves time to code more.


Inference of Parameters and return types

You don’t need to specify type of parameters in parameter list. Compiler infers the type based on context. If the type is not specified, it is inferred to be generic. If the code uses a value inconsistently in such a way there is no single inferred type, compiler reports an error.

The return type of a function is determined by the last expression in the function.


F# Inference of Parameter and return types Example

Output:

30 

F# Automatic Generalization

When code does not specify any type explicitly then the compiler considers generic type. This is called automatic generalization. It helps to write generic code without increasing complexity.

Next TopicF# String

You may also like