We refer to the type of a value being inferred because a compile-time process attempts to figure out the types of values on its own, and in the process verify the program is type safe. Type annotations (in the form v:t, meaning v of type t) are not as necessary in a language with type inference, even though the language is still strongly typed.
Generics, which will be familiar to both .NET and Java developers, have taken on an even greater role in F# because of type inference. Notice that for any expressions without type annotations the compiler can just assume generic types. For example, the function below can be genericized to have the
following type signature, even though it does not contain any type annotations from the programmer.
The compiler does something similar to that labeling automatically. From the generic labeling, determinations can already be made about the types of these functions (assuming the expression is strongly typed). First, notice f and h must yield the same type ('b). Second, the argument f is applied to must be the same type to which g is applied ('a). Using small hints like these, the compiler is often able to completely determine the types in a program with little assistance from the programmer.
Most of type inference in F# can be boiled down to two rules. First, if a function is applied to a value then the compiler may assume that value is the type the function requires. Second, if a value is bound to the result of an expression, then that value is the type the expression yields.
There are a few times when these simple rules aren't quite enough and type annotations must be added to assist the compiler. For example, when arithmetic operators are used, F# is careful not to cast one numeric type to another without explicit instructions from the programmer. That way type inference does not become a burden to intensively numerical computing.
Declare/update mutable valuelet mutable x = 0 x <- x + 1Declare/update ref valuelet x = ref 0 x := !x + 1
Another example is in method overloading. The Write method in System.Console for example has about 18 overloads. Type inference may determine the type that is passed to it, but cannot determine a value's type in the other direction. That information is required by the overloaded method to select the proper logic to dispatch for the method.
Type inference does not just aide concise notation in the face of static typing, it is also a helpful check on functional programs. When you write a piece of code, and intellisense indicates they all have the proper type, it is one more indication that gross errors were not introduced into the program. Using this tool, F# gets much of the concise notation usually only available in dynamic languages while still maintaining a fully static type system.
Basic Syntax
The "let" expression is at the core of F#'s functional syntax, and is used in a variety of ways: defining a function, defining a sequence, and so on. F# uses significant whitespace to mark block beginnings and endings.
Define any valuelet x = 2Define a function valuelet f a = a + xDefine a recursive function
Anonymous functionfun x -> Console.WriteLine (x.ToString())
The language also provides traditional imperative looping and iteration constructs, such as "if", "for" and "while". Note that "if/then" and "if/then/else" are slightly different from traditional O-O languages, in that they, like most F# expressions, must yield a value, and so both sides of the "if/then/else" must result in the same type of value.
if/thenif x=10 then printf "Was 10\n"if/then/elseif x=10 then "Was 10\n" else "Was not 10\n"For loopfor x in xs do printf "%s" x.ToString()While loop
Like most .NET languages, F# also provides some mechanism for organizing code; in fact, F# provides two, modules and namespaces, the latter acting the same way as C#/VB namespaces. Modules provide not only lexical scoping, but also space for module-level values, such as constants, fields and functions.
Basic Code Organization: namespaces, types and modules
While most identifiers in F# are immutable, in accordance with traditional functional programming principles, F# permits the definition and modification of values using the "mutable" keyword, or by taking the reference of the value in question by preceding the value with "ref". Assignment to mutable values is done using the left-hand arrow operator ("<-"). Assignment to "ref" values is done with the ":=" operator. Obtaining the value of a "ref" value uses the "!" operator.
Declare/update mutable valuelet mutable x = 0 x <- x + 1Declare/update ref valuelet x = ref 0 x := !x + 1
Function Composition
Because programs are built as composed expressions, the sequence of program logic is typically defined through function composition. Arguments to a function are evaluated prior to the function body, making programming by composition intuitive for programmers coming from a C#/VB/Java background.
Operators such as >> (for function chaining) and |> (for value piping) allow programmers to chain composed functions together in the same order in which they will be evaluated.
Composing functions to sum 5 largest array values
Composing functions starting with a value (piping)
Functional Types and Data Structures
F# also defines tuples and records, which are simple datacentric constructs useful in situations where full-blown objects would be overkill.
Discriminated unions are similar in concept to enumerated types from C# and Visual Basic, representing a bound set of values; however, discriminated unions can incorporate multiple kinds of types, including tuples and collections. Functional code will make heavy use of all three (tuples, records, and discriminated unions).
Collections
Data rich programming always involves dealing with (often large) collections of information from the filesystem, database, network or other sources. Three tools in F# make this considerably easier than other programming paradigms and languages.
tupleslet (name,value) = ("Two",2)record typestype Person = {name:string;age:int}let p = { name="Bob";age=20 }discriminated unions
Collection generators provide an easy way to create sets of data without involving a loop. Generators are available for lists, arrays, or IEnumerables (called "seq" in F#), using the [start.. finish] style syntax. In the case of arrays, the [start..finish] syntax can be used on an existing array index to "slice" the array into a new one with the given range.
Pattern matching
Pattern matching on lists (naming the head and tail with "::")
Pattern matching with constants
Pattern matching with when and _
Sequence expressions result in an IEnumerable that can be consumed by any other language on the .NET platform, and are ideal for lazy collection generation or evaluation. They often use a pattern of the form "seq { for x in col do, yield x done }" to transform collections into their evaluated result sets. Finally, higher order functions (e.g. map, fold, reduce and sum) allow programmers to ditch boiler plate code around collection processing and just pass the body of the iterator to a function. The body is often passed as an anonymous function.
List defined in 2 different ways
Array defined in 2 different ways
Array slicing (0 to 9 and 10 to end)
Sequence Expression (piped into iterator
Higher order multiply by 10, sum and print
Pattern Matching
Another core construct in the language is pattern-matching, given by the "match" keyword and a series of expressions to match against; with this construct, combined with recursion, F# is able to create stack-centric, thread-friendly versions of traditional looping code:
Each case is demarcated by a new vertical "pipe" character, and the result by the right-hand side of the "->". Note that the match clause can introduce new local bindings ("v" in the example), which will be populated for use in the expression evaluation. Pattern matching can also include "guard" expressions, given by "when"clauses. More forms are given in the F# spec.
Pattern matching
Pattern matching on lists (naming the head and tail with "::")
Pattern matching with constants
Pattern matching with when and _
More Pattern matching with _
Exceptions
F# allows developers to trap exceptions thrown by methods
that are called, as well as generate exceptions when desired. There are shortcut functions (e.g. "failwith") defined that provide a concise way to generate exceptions with custom messages.
Using the try/with syntax, developers can use the pattern matching syntax to check the type of the exception and invoke the appropriate logic.
Try catch with pattern match on type of exception
always run code after exception block
Function to throw FailureExceptionfailwith "Operation Failed"
OOP in F#
F# is a full object-oriented language in the .NET ecosystem, meaning it knows not only how to use but also how to define new class types with the full range of O-O features: fields, methods, properties, events, interfaces, inheritance, and so on.
Defining a simple class type:
The constructor is in the type declaration line, and that type is intrinsically immutable (that is, the properties FirstName, LastName and Age all have get access but not set). This is in line with traditional functional principles. To create mutable members, the F# "mutable" keyword must appear on the member to be mutable, and the explicit "get" and "set" members for each property must be established.
Types in F# can inherit from base classes or interfaces, using the "override" keyword to override inherited members:
F# can also create object expressions, which are anonymously-defined types that inherit from an existing class or interface; in many cases, this will be much quicker and easier than creating a new type.
Classes and Object Expression
Class definition
Multiple constructors
Abstract methods for an interface and its construction
Abstract methods for an abstract class and its construction
Augmenting Record types with methods
Augmenting Discriminated Unions with methods
Instantiating the type and applying the method
Augmenting existing types with methods
Object expression
F# Expressions
Below is a table of F# expressions for reference. Some of these can be typed into the interactive shell. Feel free to fire up the interactive shell and type these in yourself.
Type Notation
valuex : intfunction that is applied to an int, and yields an intf:(int -> int)function in a functionmap:('a->'b)->'a list->'b listgenericsf:'a -> 'bannotate an argumentlet toStr (x:int) = x.ToString()
F# Interactive Commands
Reference a dll#r#r "System.Windows.Forms";;Load an F# code file#load#load "Module.fs";;Add a directory to the search path#I#I @"c:\lib";;Refer to the last yielded result from an expressionitprintf "%O\n" it
Time the evaluation of an expression#time
Units of Measure
Declare a Unittype [<Measure>] seconds type [<Measure>] metersManipulate unit values
Break the unit
Async Combinators
Used to create and manipulate async expressions.
Build an async expression using the continuations for continue, cancel and exceptionAsync.Primitive (con,can,exn)Build an async expression using the begin and end methods providedAsync.BuildPrimitive (b,e)Yield an async expression that, when executed, runs the sequence of async expressions in parallel and yields an array of resultsaExprs|> Async.Parallel|> printf "%A\n"Fork the expressionlet! child = Async.StartChild aExprFork the expression and yield a threading task that executes the operation.let! tsk = Async.StartChildAsTask aExprManipulate the current threadsync.SwitchToGuiThread Async.SwitchToNewThread Async.SwitchToThreadPool
Async Expression Execution
Run the computation of type Async<T> and yield the TAsync.RunSynchronously aExprProvide three continuations for continue, exception and cancellation to be evaluated when the expression yields a result
Fire and Forget in the thread poolAsync.StartYield a Threading Task that executes the computationAsync.StartAsTaskApply a function to every element of a sequence in parallel
Active Patterns
Notice that the Active Pattern creates a function view on an object oriented architecture. The point of this approach is to marry functional languages on top of existing object oriented architectures and class libraries. The combination of views on the objects that result in functional types, and pattern matching can make functional programming on an object oriented framework more readable and clear. The approach
also encourages object oriented extensions where they make sense to existing functional architectures while minimizing clutter.
Defining Patterns
Matching Active Patternsmatch xml with | NoXml -> printf "Doc was empty!" | Xml(xml) -> printf "%O" xmlPartial (Incomplete) Active Patterns that read a set of file contents and yield different types, depending on the specific views of the object
Pattern matching piece to consume the active pattern setup above
Error Messages
Included below are some common error messages with F#. The areas that tend to trip up people beginning F# are usually exacerbated by misunderstanding the error messages. But a clear understanding of these error messages makes your F# programming a cinch. If one of these messages pops up when you are trying to compile, or drop some code in the interactive session then use the reference below to clarify the problem. The first column of the table describes the problem, the second column is the error message reference, and the third column gives examples for recreating the error.
.
F# Resources
http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/
F# - Downloads
http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/release.aspx
Microsoft F# Developer Center
http://msdn.microsoft.com/en-us/fsharp/default.aspx
F# Samples
http://www.codeplex.com/fsharpsamples