F Sharp programming language
Encyclopedia
F# is a multi-paradigm programming language
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 inference
Type 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 unit
Unit type
In 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 cons
Cons
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,

type A =
| ConstructorX of string
| ConstructorY of int

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 functions
Lambda 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 union
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...

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 syntax
Metaprogramming
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 evaluated
Lazy 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 in

let asynctask = async
{
let req = WebRequest.Create(url)
let! response = req.GetResponseAsync
use stream = response.GetResponseStream
use streamreader = new System.IO.StreamReader(stream)
return streamreader.ReadToEnd
}

The let! allows the rest of the async block to be defined as the delegate and passed as the callback function
Callback (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:

(* This is a comment *)
(* Sample hello world program *)
printfn "Hello World!"


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#:

let rec factorial n =
match n with
| 0 -> 1
| _ -> n * factorial (n - 1)


Recursive function examples:

(* Print a list of numbers recursively *)
let rec printList lst =
match lst with
| [] ->
| h :: t ->
printf "%d\n" h
printList t

(* Same thing, using matching against list elements *)
let rec printList2 l =
match l with
| [] ->
| h :: t -> printfn "%A" h
printList2 t

(* Using shorthand for match *)
let rec printList3 = function
| [] ->
| h :: t -> printfn "%A" h
printList3 t

(* Or, using a higher-order function *)
let printlist4 lst = List.iter (printfn "%A") lst



(* Fibonacci Number formula *)
let rec fib n =
match n with
| 0 | 1 -> n
| _ -> fib (n - 1) + fib (n - 2)

(* An alternative approach - a lazy recursive sequence of Fibonacci numbers *)
let rec fibs = Seq.cache <| seq { yield! [1; 1]
for x, y in Seq.zip fibs <| Seq.skip 1 fibs -> x + y }

(* Another approach - a lazy infinite sequence of Fibonacci numbers *)
let fibSeq = Seq.unfold (fun (a,b) -> Some(a+b, (b, a+b))) (1,1)

(* Print even fibs *)
[1 .. 10]
|> List.map fib
|> List.filter (fun n -> (n % 2) = 0)
|> printlist

(* Same thing, using sequence expressions *)
[ for i in 1..10 do
let r = fib i
if r % 2 = 0 then yield r ]
|> printlist



(* Sample Windows Forms Program *)

(* We need to open the System library for the STAThreadAttribute class *)
open System

(* We need to open the Windows Forms library *)
open System.Windows.Forms

(* Create a window and set a few properties *)
let form = new Form(Visible=true, TopMost=true, Text="Welcome to F#")

(* Create a label to show some text in the form *)
let label =
let temp = new Label
let x = 3 + (4 * 5)
(* Set the value of the Text*)
temp.Text <- sprintf "x = %d" x
(* Remember to return a value! *)
temp

(* Add the label to the form *)
form.Controls.Add(label)

(* Finally, run the form *)
[]
Application.Run(form)



(* Async workflows sample (parallel CPU and I/O tasks) *)

(* A very naive prime number detector *)
let isPrime (n:int) =
let bound = int (System.Math.Sqrt(float n))
seq {2 .. bound} |> Seq.exists (fun x -> n % x = 0) |> not

(* We are using async workflows *)
let primeAsync n =
async { return (n, isPrime n) }

(* Return primes between m and n using multiple threads *)
let primes m n =
seq {m .. n}
|> Seq.map primeAsync
|> Async.Parallel
|> Async.RunSynchronously
|> Array.filter snd
|> Array.map fst

(* Run a test *)
primes 1000000 1002000
|> Array.iter (printfn "%d")

See also

  • C#
  • Clojure
    Clojure
    Clojure |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....

  • Haskell
    Haskell (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

External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK