Saturday, November 19, 2011

F# Function

Function Definition
F# function is defined as values, except everything after the name of the function serves as parameters. Herez incrementor function

> let incrementer x = x+1;;

val incrementer : int->int

> incrementer 6;;
val it:int=7

Unlike C#, F# has no return keyword; it returns the last evaluted expression.

Type Inference
F# is statically typed, calling incrementer function with floating value will result in a compilation error as:

> incrementer 6.0;;

error FS0001: This expression has type float

Reason is becaz of type inference, which requires explicitly state of the types. Type inference is different from dynamic typing. Though, F# allows to omit types, it doesn't mean that type checking is not enforced at compile time.

Generic Function
Type of generic parameter can have the name of any valid identifier prefixed with an apostrophe. Below code defines incrementer function using a type annotation that forces the parameter x to be generic.

> let incrementer (x:'a) = x+1;;

val incrementer : 'a->'a

Writing generic code is important for maximizing code reuse. In this example, parameter 'a can be an int, float, string, user defined type, etc.

No comments:

Post a Comment