F Sharp programming language
Encyclopedia
F# is a multi-paradigm programming language
, targeting the .NET Framework
, that encompasses functional programming
as well as imperative
and object-oriented programming
disciplines. It is a variant of ML and is largely compatible with the OCaml implementation. F# was initially developed by Don Syme
at Microsoft Research
but is now being developed at Microsoft
Developer Division and is being distributed as a fully supported language in the .NET Framework
and Visual Studio
as part of Visual Studio 2010.
. As a result, data types do not need to be explicitly declared by the programmer; they will be deduced by the compiler during compilation. However, F# also allows explicit data type declaration. Being a CLI compliant language, F# supports all CLI types and objects but it extends the type system and categorizes types as immutable type
s or mutable types. CLI objects classify as mutable types (which can be edited in-place), and are used to provide an object-oriented programming
model. Immutable types (editing such a type creates a new instance without overwriting the older one) are primarily used for functional programming
.
Like ML, F# includes a functional programming component supporting eager evaluation
. For functional programming, it provides several constructs and a set of immutable types: tuples, records, discriminated unions and lists.
An n-tuple represents a collection of n values, where n ≥ 0. The value n is called the arity
of the tuple. The type
A record is a specialization of tuple where the data members are named, as in
The list type is a regular linked list
represented either using a
operator) or a shorthand as
The other sort of algebraic data type
mentioned, "discriminated unions
" (type-safe versions of C unions
), can be defined to hold a value of any of a pre-defined type. For example,
can hold values as instantiated by either constructor. The type of the values the constructors will act on can be defined as well.
Constructors are used to create a view of the data type different from the actual implementation, as required for supporting the Active Patterns concept. Data types are created with the
F# uses pattern matching
to resolve names into values. It is also used when accessing discriminated unions. Functions using a discriminated union provide different expressions to be invoked, associated with the data type in the union. The union is matched against these data types, and the expression associated with the match is invoked. F# also supports the Active Patterns pattern. It is used, for example, when a type needs to provide multiple views. For example, an exponential number will provide both the final value, as well as the base and exponents.
All functions in F# are instances of the
and closures as well. Like other functional programming languages, F# allows function composition
using the
The F# extended type system is implemented as generic
.NET types. The Record type creates a .NET class with the field names as properties. Tuples are generic classes of type
s. Functions are of type
F#, like other .NET languages, can use .NET types and objects, using an imperative object-oriented style of programming. For imperative programming, F# supports
to support embedding custom domain-specific languages within the F# language itself.
F# provides sequence expressions that allows for a defining a sequence block (
, i. e., the collection is processed and results yielded on-demand. It can be used for filtering and is the basis of support for LINQ
queries. Sequence expressions are generalized as Computation Expressions which are equivalent to monads.
Sequence expressions and computation expressions are also used for creating asynchronous workflows. An asynchronous workflow is defined as a sequence of commands inside a
The
of an asynchronous operation. This helps deal with inversion of control
issues. The async block is invoked using the
F# comes with a Microsoft Visual Studio
language service that integrates it with the IDE. With the language service installed, Visual Studio can be used to create F# projects and the Visual Studio debugger used to debug F# code. In addition, it comes with a Visual Studio-hosted interactive console that executes F# code as it is being written.
SharpDevelop
supports F# as well since version 3.0.
LinqPad
supports F# as well since version 2.x.
A simple example that is often used to demonstrate the syntax of functional languages is the factorial function for non-negative 32-bit integers, here shown in F#:
Recursive function examples:
Multi-paradigm programming language
Programming languages can be grouped by the number and types of paradigms supported.-Paradigm summaries:A concise reference for the programming paradigms listed in this article....
, targeting the .NET Framework
.NET Framework
The .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allows language interoperability...
, that encompasses functional programming
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...
as well as imperative
Imperative programming
In computer science, imperative programming is a programming paradigm that describes computation in terms of statements that change a program state...
and object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...
disciplines. It is a variant of ML and is largely compatible with the OCaml implementation. F# was initially developed by Don Syme
Don Syme
Don Syme is an Australian computer scientist and a Principal Researcher at Microsoft Research, Cambridge, U.K. He is the designer and architect of the F# programming language, described by a reporter as being regarded as "the most original new face in computer languages since Bjarne Stroustrup...
at Microsoft Research
Microsoft Research
Microsoft Research is the research division of Microsoft created in 1991 for developing various computer science ideas and integrating them into Microsoft products. It currently employs Turing Award winners C.A.R. Hoare, Butler Lampson, and Charles P...
but is now being developed at Microsoft
Microsoft
Microsoft Corporation is an American public multinational corporation headquartered in Redmond, Washington, USA that develops, manufactures, licenses, and supports a wide range of products and services predominantly related to computing through its various product divisions...
Developer Division and is being distributed as a fully supported language in the .NET Framework
.NET Framework
The .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allows language interoperability...
and Visual Studio
Microsoft Visual Studio
Microsoft Visual Studio is an integrated development environment from Microsoft. It is used to develop console and graphical user interface applications along with Windows Forms applications, web sites, web applications, and web services in both native code together with managed code for all...
as part of Visual Studio 2010.
Overview
F# is a strongly typed language that uses type inferenceType inference
Type inference refers to the automatic deduction of the type of an expression in a programming language. If some, but not all, type annotations are already present it is referred to as type reconstruction....
. As a result, data types do not need to be explicitly declared by the programmer; they will be deduced by the compiler during compilation. However, F# also allows explicit data type declaration. Being a CLI compliant language, F# supports all CLI types and objects but it extends the type system and categorizes types as immutable type
Immutable object
In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created...
s or mutable types. CLI objects classify as mutable types (which can be edited in-place), and are used to provide an object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...
model. Immutable types (editing such a type creates a new instance without overwriting the older one) are primarily used for functional programming
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...
.
Like ML, F# includes a functional programming component supporting eager evaluation
Eager evaluation
In computer programming, eager evaluation or greedy evaluation is the evaluation strategy in most traditional programming languages. In eager evaluation an expression is evaluated as soon as it gets bound to a variable. The term is typically used to contrast lazy evaluation, where expressions are...
. For functional programming, it provides several constructs and a set of immutable types: tuples, records, discriminated unions and lists.
An n-tuple represents a collection of n values, where n ≥ 0. The value n is called the arity
Arity
In logic, mathematics, and computer science, the arity of a function or operation is the number of arguments or operands that the function takes. The arity of a relation is the dimension of the domain in the corresponding Cartesian product...
of the tuple. The type
unitUnit typeIn the area of mathematical logic, and computer science known as type theory, a unit type is a type that allows only one value . The carrier associated with a unit type can be any singleton set. There is an isomorphism between any two such sets, so it is customary to talk about the unit type and...
corresponds to the 0-tuple and it has one value only:
, which conveys no information. The type unit
is used to implement functions that need no input and/or return no value. A 3-tuple would be represented as (A, B, C)
, where A, B and C are values of possibly different types. A tuple can be used only to store values when the number of values is known at design-time and stays constant throughout execution.A record is a specialization of tuple where the data members are named, as in
{ Name:string; Age:int }
. Records can be created as { Name="AB"; Age=42 }
. The with
keyword is used to create a copy of a record, as in { r with Name="CD" }
, which creates a new record by copying r
and changing the value of the Name
field (assuming the record created in the last example was named r
).The list type is a regular linked list
Linked list
In computer science, a linked list is a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of a datum and a reference to the next node in the sequence; more complex variants add additional links...
represented either using a
head::tail
notation (::
is the consCons
In computer programming, cons is a fundamental function in most dialects of the Lisp programming language. cons constructs memory objects which hold two values or pointers to values. These objects are referred to as cells, conses, non-atomic s-expressions , or pairs...
operator) or a shorthand as
[item1; item2; item3]
. An empty list is written []
.The other sort of algebraic data type
Algebraic data type
In computer programming, particularly functional programming and type theory, an algebraic data type is a datatype each of whose values is data from other datatypes wrapped in one of the constructors of the datatype. Any wrapped datum is an argument to the constructor...
mentioned, "discriminated unions
Tagged union
In computer science, a tagged union, also called a variant, variant record, discriminated union, or disjoint union, is a data structure used to hold a value that could take on several different, but fixed types. Only one of the types can be in use at any one time, and a tag field explicitly...
" (type-safe versions of C unions
Union (computer science)
In computer science, a union is a value that may have any of several representations or formats; or a data structure that consists of a variable which may hold such a value. Some programming languages support special data types, called union types, to describe such values and variables...
), can be defined to hold a value of any of a pre-defined type. For example,
can hold values as instantiated by either constructor. The type of the values the constructors will act on can be defined as well.
Constructors are used to create a view of the data type different from the actual implementation, as required for supporting the Active Patterns concept. Data types are created with the
type
keyword. F# uses the let
keyword for binding type values to a name (variable).F# uses pattern matching
Pattern matching
In computer science, pattern matching is the act of checking some sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact. The patterns generally have the form of either sequences or tree structures...
to resolve names into values. It is also used when accessing discriminated unions. Functions using a discriminated union provide different expressions to be invoked, associated with the data type in the union. The union is matched against these data types, and the expression associated with the match is invoked. F# also supports the Active Patterns pattern. It is used, for example, when a type needs to provide multiple views. For example, an exponential number will provide both the final value, as well as the base and exponents.
All functions in F# are instances of the
function
type, and are immutable as well. Functions can be curried. Being an instance of a type, functions can be passed as arguments to other functions, resulting in higher order functions. F# supports lambda functionsLambda calculus
In mathematical logic and computer science, lambda calculus, also written as λ-calculus, is a formal system for function definition, function application and recursion. The portion of lambda calculus relevant to computation is now called the untyped lambda calculus...
and closures as well. Like other functional programming languages, F# allows function composition
Function composition
In mathematics, function composition is the application of one function to the results of another. For instance, the functions and can be composed by computing the output of g when it has an argument of f instead of x...
using the
>>
operator. Every statement in F#, including if
statements and loops, is a composable expression with a definite return type as well. Functions and expressions that do not return any value have a return type of unit
.The F# extended type system is implemented as generic
Generic programming
In a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...
.NET types. The Record type creates a .NET class with the field names as properties. Tuples are generic classes of type
Tuple<_,_>
. The number of type parameters define the number and types of the elements in the tuple. Discriminated unions are implemented as tagged unionTagged union
In computer science, a tagged union, also called a variant, variant record, discriminated union, or disjoint union, is a data structure used to hold a value that could take on several different, but fixed types. Only one of the types can be in use at any one time, and a tag field explicitly...
s. Functions are of type
FastFunc<_,_>
with type parameters specifying the parameter and return types.F#, like other .NET languages, can use .NET types and objects, using an imperative object-oriented style of programming. For imperative programming, F# supports
for
and while
loops, arrays (created with the [| ... |]
syntax, and number sequences written in shorthand as in 1 .. 25
) and support for creating Object types
(equivalent to .NET classes). F# also allows extending the syntaxMetaprogramming
Metaprogramming is the writing of computer programs that write or manipulate other programs as their data, or that do part of the work at compile time that would otherwise be done at runtime...
to support embedding custom domain-specific languages within the F# language itself.
F# provides sequence expressions that allows for a defining a sequence block (
seq { ... }
or [ ... ]
or [| ... |]
) encapsulating constructs (either functions, conditional expressions or loops) that act on a collection and another function (or lambda), such that the function is invoked on the results yielded from the collection collection-processing expressions. For example, seq { for b in 0 .. 25 do if b < 15 then yield b*b }
is a sequence expression that forms a sequence of squares of numbers from 0 to 14 by filtering out numbers from the range of numbers from 0 to 25. The sequence is lazily evaluatedLazy evaluation
In programming language theory, lazy evaluation or call-by-need is an evaluation strategy which delays the evaluation of an expression until the value of this is actually required and which also avoids repeated evaluations...
, i. e., the collection is processed and results yielded on-demand. It can be used for filtering and is the basis of support for LINQ
LINQ
Linq is a word-based card game from Endless Games, introduced at the American International Toy Fair in 2005.Game play requires at least four players, two of whom are dealt cards with the same word, while the others receive blanks. The goal is to gain points by correctly naming the players with...
queries. Sequence expressions are generalized as Computation Expressions which are equivalent to monads.
Sequence expressions and computation expressions are also used for creating asynchronous workflows. An asynchronous workflow is defined as a sequence of commands inside a
async{ ... }
, as inThe
let!
allows the rest of the async block to be defined as the delegate and passed as the callback functionCallback (computer science)
In computer programming, a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower-level software layer to call a subroutine defined in a higher-level layer....
of an asynchronous operation. This helps deal with inversion of control
Inversion of Control
In software engineering, Inversion of Control is an abstract principle describing an aspect of some software architecture designs in which the flow of control of a system is inverted in comparison to procedural programming....
issues. The async block is invoked using the
Async.Run
function. Multiple async blocks are executed in parallel using the Async.Parallel
function that takes a list of async
objects (in the example, asynctask
is an async object) and creates another async object to run the tasks in the lists in parallel. The resultant object is invoked using Async.Run
.F# comes with a Microsoft Visual Studio
Microsoft Visual Studio
Microsoft Visual Studio is an integrated development environment from Microsoft. It is used to develop console and graphical user interface applications along with Windows Forms applications, web sites, web applications, and web services in both native code together with managed code for all...
language service that integrates it with the IDE. With the language service installed, Visual Studio can be used to create F# projects and the Visual Studio debugger used to debug F# code. In addition, it comes with a Visual Studio-hosted interactive console that executes F# code as it is being written.
SharpDevelop
SharpDevelop
SharpDevelop is a free and open source integrated development environment for the Microsoft .NET, Mono, Gtk# and Glade# platforms, and supports development in C#, Visual Basic .NET, Boo, F#, IronPython and IronRuby programming languages.It was designed as a free and lightweight alternative to...
supports F# as well since version 3.0.
LinqPad
Linqpad
LINQPad is a free software utility for Microsoft .NET developers using LINQ. It allows developers to interactively query SQL databases and other data sources such as OData or WCF Data Services using LINQ...
supports F# as well since version 2.x.
Examples
A few small samples follow:A simple example that is often used to demonstrate the syntax of functional languages is the factorial function for non-negative 32-bit integers, here shown in F#:
Recursive function examples:
See also
- C#
- ClojureClojureClojure |closure]]") is a recent dialect of the Lisp programming language created by Rich Hickey. It is a general-purpose language supporting interactive development that encourages a functional programming style, and simplifies multithreaded programming....
- HaskellHaskell (programming language)Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...
- Mercury
- ML
- Nemerle
- OCaml
- Scala