F Sharp (programming language): Difference between revisions
rewrite |
|||
Line 1: | Line 1: | ||
{{DISPLAYTITLE:F#}} |
|||
{{pound|F#}} |
{{pound|F#}} |
||
{{Otheruses4|the programming language|the musical note|F♯}} |
{{Otheruses4|the programming language|the musical note|F♯}} |
||
Line 21: | Line 20: | ||
|website = [http://research.microsoft.com/fsharp/fsharp.aspx Microsoft Research's website for F#] |
|website = [http://research.microsoft.com/fsharp/fsharp.aspx Microsoft Research's website for F#] |
||
}} |
}} |
||
'''F#''' (pronounced '''F Sharp''') is a [[multi-paradigm programming language|multi-paradigm]] [[programming language]], targeting the [[.NET Framework]], that encompasses [[functional programming]] as well as [[imperative programming|imperative]] [[object-oriented programming]] disciplines. It is a variant of [[ML (programming language)|ML]] and is largely compatible with the [[OCaml]] implementation. F# was intially developed by [[Don Syme]] at [[Microsoft Research]] but is now being developed at [[Microsoft]] Developer Division and will be a productized as fully supported language in the [[.NET Framework]] and [[Microsoft Visual Studio|Visual Studio]] ecosystem.<ref>{{cite web | url = http://blogs.msdn.com/somasegar/archive/2007/10/17/f-a-functional-programming-language.aspx | title = F# - A functional Programming Language | author = S. Somasegar | accessdate = 2007-10-18}}</ref>. |
|||
'''F#''' (pronounced "F sharp") is a [[functional programming|functional]] and [[object oriented]] [[programming language]] for the [[Microsoft .NET]] platform. A strength of F# is its setting within .NET. A key design aim is seamless .NET interoperability, both via direct use of .NET APIs from F# and authorship of natural .NET components in F#. So, the main F# libraries are the .NET libraries themselves (e.g. [[Windows Forms]], and [[ASP.NET]], as well as alternatives like [[Gtk Sharp|Gtk#]]). A [[Visual Studio]] [[plugin]] provides a graphical development environment, including features such as background type-checking with feedback under the [[pointing device]], which assists with [[type inference]]. |
|||
==Overview== |
|||
F# was initially developed by [[Microsoft Research]], but now is being developed by [[Microsoft]] developer division, after it was announced on [[October 17]], [[2007]] that F# will be productized as a fully integrated language in [[Visual Studio]]<ref>{{cite web | url = http://blogs.msdn.com/somasegar/archive/2007/10/17/f-a-functional-programming-language.aspx | title = F# - A functional Programming Language | author = S. Somasegar | accessdate = 2007-10-18}}</ref>. The latest released version, 1.9.3, was released on [[November 30]], [[2007]]<ref>{{cite web | url = http://blogs.msdn.com/dsyme/archive/2007/11/30/f-1-9-3-candidate-release-now-available.aspx | title = F# 1.9.3 Candidate Release Now Available | author = D. Syme | accessdate = 2007-12-10}}</ref>. |
|||
F# is a [[strong typing|strongly-typed]] language that uses [[type inference]]. As a result, data types need not be explicitly declared by the programmer, rather will be deduced by the compiler during compilation. However, F# also allows explicit data type declaration. Being a [[.NET languages|.NET language]], F# supports .NET types and objects. But it extends the type system and categorizes types as [[immutable object|immutable type]]s or mutable types. .NET objects classify as mutable types (which can be edited in-place), and are used to provide an [[object-oriented programming]] model. Immutable types (editing which creates a new instance without overwriting the older one) are primarily used for [[functional programming]]. |
|||
Like [[ML (programming language)|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''.<ref name="overview"/> A ''tuple'' represents a collection of more than one values. It is represented as <code>(A, B)</code>, where A and B can be of any type. 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 <code>{ Name: string, Age:int }</code>. Records can be created as <code>{ Name="AB", Age=32 }</code> The <code>with</code> keyword is used to create a copy of a record, as in <code>{ r with Name="CD" }</code> creates a new record that by changing the value of the <code>Name</code> field in record <code>r</code> (assuming the record created in the last example was named <code>r</code>). The ''list'' type is a regular [[linked list]] represented either using a <code>head::tail</code> notation (composition using the <code>::</code> - <code>cons</code> - operator) or a shorthand as <code>[elem1, elem2, elem3]</code>. An empty list is defined as <code>[]</code>. A ''discriminated union'' (which is functionally like a type-safe version of C union) can be defined to hold a value of any of a pre-defined type. For example, |
|||
The core language is similar to that of the [[Objective Caml]] language: both are members of the [[ML programming language]] family. Like the [[Scala programming language]], it implements a functional programming language on top of a platform originally designed for object-oriented programming paradigm. |
|||
<code> |
|||
type A = |
|||
| TypeConstructorA of string |
|||
| TypeConstructorB of int |
|||
</code> |
|||
can hold values as instantiated by either [[type constructor]]. The type of the values the type constructors will act on can be defined as well. Type constructors are used to create a view of the data type different from the actual implementation, as required for supporting the [[Active Patterns]] concept.<ref name="overview"/> Data types are created with the <code>Type</code> keyword. F# uses the <code>let</code> keyword for binding type values to a name (variable).<ref name="overview">{{cite web | url = http://tomasp.net/articles/fsharp-i-introduction/article.pdf | title = F# Language Overview | accessdate = 2007-12-14}}</ref> |
|||
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 assocated 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.<ref name="overview"/> |
|||
There is a standard library for F#, designed to be largely compatible with the OCaml standard library. Since the two languages also share a common language subset, it can thus be quite practical to compile a single codebase with both. This enables core Caml code to be ported to the .NET world, and core F# code to run with OCaml. Maintaining this basic compatibility is one of the primary goals of the project. |
|||
All functions in F# are instances of the <code>function</code> type, and are immutable as well.<ref name="overview"/> Functions can either be [[curry function|curried]] or in uncurried form. Being an instance of a type, functions can be passed as arguments to other functions, resulting in [[higher order function]]s. F# supports [[lambda function]]s and [[closure (computing)|closure]]s as well.<ref name="overview"/> Like other functional programming languages, F# allows [[function composition]] using the <code>>></code> operator. Every statement and F#, including if-statements and loops, are composable expressions with a definite return type as well.<ref name="overview"/> Functions and expressions that do not return any value have a return type of <code>unit</code>. |
|||
As a research project, F# demonstrates how .NET enables interoperability between different [[programming paradigm]]s. It showcases a set of extensions to .NET's intermediate language IL, called ILX, which demonstrate how a strict [[currying|curried]] functional language may be compiled efficiently. |
|||
The F# extended type system is implemented as [[generic programming|generic]] .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 typle. Discriminated unions are implemented as [[tagged union]]s. Functions are of type <code>FastFunc<_,_></code> with type parameters specifying the parameter and return types.<ref>{{cite web | url = http://research.microsoft.com/fsharp/manual/export-interop.aspx | title = F# from C# and other .NET Languages | accessdate = 2007-12-14}}</ref> |
|||
== Applications == |
|||
F#, like other .NET languages, can use .NET types and objects, using an imperative object-oriented style of programming. For imperative programming, F# supports <code>for</code> and <code>while</code> [[loop]]s, [[array]]s (created with the <code>[| … |]</code> syntax, and number sequences written in shorthand as in <code>1 .. 25</code>) and support for creating <code>Object types</code> (equivalent to .NET classes).<ref name="overview"/> F# also allows [[metaprogramming|extending the syntax]] to support embedding custom [[domain specific language]]s within the F# language itself. <ref name="overview"/> |
|||
The F# programming language has many applications ranging from scripting to cross-platform application development. |
|||
F# provides ''sequence expressions''<ref name="seq"/> that allows for a defining a sequence block (<code>seq { … }</code> or <code>[ … ]</code> or <code>[| … |]</code>) encapsulating constructs (either functions, conditional expressions or loops) that act on a collection such that the results and another function (or lambda), such that the function is invoked on the results yielded from the collection collection-processing expressions. For example, <code>[for b in 0 .. 25 when b < 15 -> (b*b)]</code> is a sequence expression that forms a list of squares of numbers from 0 to 14 by filtering out numbers from an array of 0 to 25. The sequence is [[lazy evaluation|lazily evaluated]], 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 [[monad (functional programming)|monad]]s.<ref name="seq">{{cite web | url = http://blogs.msdn.com/dsyme/archive/2007/09/22/some-details-on-f-computation-expressions-aka-monadic-or-workflow-syntax.aspx | title = Some Details on F# Computation Expressions | accessdate = 2007-12-14}}</ref> |
|||
Stephen Tse at University of Pennsylvania is developing Fjavac<ref>http://www.cis.upenn.edu/~stse/javac/</ref>, a Java 5 compiler. Fjavac is developed in OCaml, but can be cross-compiled with F# on both Microsoft.NET and Mono. |
|||
Sequence expressions and computation expressions are also used for creating ''asynchronous workflows''.<ref name="aw"/> An asynchronous workflow is defined as a sequence of commands inside a <code>async{ … }</code>, as in |
|||
The properties of the F# language and environment make it an ideal platform for scientific computing, filling the gap between low-level but high-performance numerical languages like [[Fortran]] and high-level but slow languages like [[Mathematica]]. F# provides the performance of a compiled language (typically close to that of [[C_Sharp|C#]])<ref>http://research.microsoft.com/fsharp/fsharp.aspx</ref> with the sophisticated language features of high-level languages, including safety, static typing, pattern matching, views, higher-order functions and currying. |
|||
<code> |
|||
let asyntask = async |
|||
{ |
|||
let req = WebRequest.Create(url) |
|||
let! response = req.GetResponseAsync() |
|||
use stream = response.GetResponseStream() |
|||
use streamreader = new System.IO.StreamReader(stream) |
|||
return streamreader.ReadToEnd() |
|||
} |
|||
</code> |
|||
The <code>let!</code> allows the rest of the async block to be defined as the delegate and passed as the [[callback (computer science)|callback function]] of an asynchronous operation. This helps deal with [[inversion of control]] issues.<ref name="aw"/> The async block is invoked using the <code>Async.Run</code> function. Multiple async blocks are executed parallely using the <code>Async.Parallel</code> function that takes a list of <code>async</code> objects (in the example, <code>asynctask</code> is an async object) and creates another async object to run the tasks in the lists in parallel. The resultant object is invoked using <code>Async.Run</code>.<ref name="aw">{{cite web | url = http://blogs.msdn.com/dsyme/archive/2007/10/11/introducing-f-asynchronous-workflows.aspx | title = Introducing F# Asynchronous Workflows | accessdate = 2007-12-14}}</ref> |
|||
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. |
|||
The F# environment includes the ability to run interactive sessions, allowing users to run pieces of code at will, collecting and analysing the results without having to compile whole programs. Moreover, visualizations can be spawned from interactive sessions, giving F# the essential functionality of many expensive technical computing environments. |
|||
F# also provides access to a foreign function interface, allowing libraries such as [[LAPACK]] and [[FFTW]] to be used with only a small amount of binding code.{{Fact|date=September 2007}} |
|||
== Examples == |
== Examples == |
||
Line 121: | Line 136: | ||
F# is compatible with the [[XNA Game Studio Express]] product, which permits construction of games for Windows and for the Xbox 360. |
F# is compatible with the [[XNA Game Studio Express]] product, which permits construction of games for Windows and for the Xbox 360. |
||
== See also == |
|||
* [[C Sharp programming language|C#]] |
|||
* [[OCaml]] |
|||
==References== |
==References== |
||
{{reflist}} |
{{reflist}} |
||
== Books == |
|||
Three books on F# are due to be published in 2007, including the first formal description of the language by its creator. |
|||
==External links== |
==External links== |
||
==External links== |
|||
* [http://research.microsoft.com/fsharp/fsharp.aspx Microsoft Research's website for F#] |
* [http://research.microsoft.com/fsharp/fsharp.aspx Microsoft Research's website for F#] |
||
* [http://research.microsoft.com/fsharp/manual F# Manual] |
* [http://research.microsoft.com/fsharp/manual F# Manual] |
||
* [http://fsharp.name F Sharp] |
|||
* [http://cs.hubfs.net/ hubFS: The place for F# - F# news, forums and blogs] |
|||
* [http://blogs.msdn.com/dsyme Don Syme's web log, a key source of information on F#] |
* [http://blogs.msdn.com/dsyme Don Syme's web log, a key source of information on F#] |
||
* [http://blogs.msdn.com/somasegar/archive/2007/10/17/f-a-functional-programming-language.aspx S. Somasegar, VP of Developer Division at Microsoft, announcing Microsoft will productionize F#] |
|||
* [http://strangelights.com/fsharp/Wiki/default.aspx F# Wiki] |
* [http://strangelights.com/fsharp/Wiki/default.aspx F# Wiki] |
||
* [http://grammerjack.spaces.live.com/blog/cns!F2629C772A178A7C!156.entry How to Write XNA Game Studio Express Games with F#] |
|||
{{DotNET}} |
{{DotNET}} |
Revision as of 10:17, 14 December 2007
#
Paradigm | multi-paradigm: imperative, functional, object-oriented |
---|---|
Designed by | Microsoft Research |
Developer | Microsoft Research |
First appeared | 2005 (last revised 2007) |
Stable release | 1.9.3
/ November 30, 2007 |
Typing discipline | static, strong, inferred |
OS | Cross-platform (.NET Framework, Mono) |
License | Microsoft Research Shared Source license agreement ("MSR-SSLA") |
Website | Microsoft Research's website for F# |
Influenced by | |
Objective Caml, C# |
F# (pronounced F Sharp) is a multi-paradigm programming language, targeting the .NET Framework, that encompasses functional programming as well as imperative object-oriented programming disciplines. It is a variant of ML and is largely compatible with the OCaml implementation. F# was intially developed by Don Syme at Microsoft Research but is now being developed at Microsoft Developer Division and will be a productized as fully supported language in the .NET Framework and Visual Studio ecosystem.[1].
Overview
F# is a strongly-typed language that uses type inference. As a result, data types need not be explicitly declared by the programmer, rather will be deduced by the compiler during compilation. However, F# also allows explicit data type declaration. Being a .NET language, F# supports .NET types and objects. But it extends the type system and categorizes types as immutable types or mutable types. .NET objects classify as mutable types (which can be edited in-place), and are used to provide an object-oriented programming model. Immutable types (editing which 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.[2] A tuple represents a collection of more than one values. It is represented as (A, B)
, where A and B can be of any type. 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=32 }
The with
keyword is used to create a copy of a record, as in { r with Name="CD" }
creates a new record that by changing the value of the Name
field in record r
(assuming the record created in the last example was named r
). The list type is a regular linked list represented either using a head::tail
notation (composition using the ::
- cons
- operator) or a shorthand as [elem1, elem2, elem3]
. An empty list is defined as []
. A discriminated union (which is functionally like a type-safe version of C union) can be defined to hold a value of any of a pre-defined type. For example,
type A =
| TypeConstructorA of string
| TypeConstructorB of int
can hold values as instantiated by either type constructor. The type of the values the type constructors will act on can be defined as well. Type constructors are used to create a view of the data type different from the actual implementation, as required for supporting the Active Patterns concept.[2] Data types are created with the
Type
keyword. F# uses the let
keyword for binding type values to a name (variable).[2]
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 assocated 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.[2]
All functions in F# are instances of the function
type, and are immutable as well.[2] Functions can either be curried or in uncurried form. Being an instance of a type, functions can be passed as arguments to other functions, resulting in higher order functions. F# supports lambda functions and closures as well.[2] Like other functional programming languages, F# allows function composition using the >>
operator. Every statement and F#, including if-statements and loops, are composable expressions with a definite return type as well.[2] Functions and expressions that do not return any value have a return type of unit
.
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 Tuple<_,_>. the number of type parameters define the number and types of the elements in the typle. Discriminated unions are implemented as tagged unions. Functions are of type FastFunc<_,_>
with type parameters specifying the parameter and return types.[3]
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).[2] F# also allows extending the syntax to support embedding custom domain specific languages within the F# language itself. [2]
F# provides sequence expressions[4] that allows for a defining a sequence block (seq { … }
or [ … ]
or [| … |]
) encapsulating constructs (either functions, conditional expressions or loops) that act on a collection such that the results and another function (or lambda), such that the function is invoked on the results yielded from the collection collection-processing expressions. For example, [for b in 0 .. 25 when b < 15 -> (b*b)]
is a sequence expression that forms a list of squares of numbers from 0 to 14 by filtering out numbers from an array of 0 to 25. The sequence is lazily evaluated, 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.[4]
Sequence expressions and computation expressions are also used for creating asynchronous workflows.[5] An asynchronous workflow is defined as a sequence of commands inside a async{ … }
, as in
let asyntask = 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 of an asynchronous operation. This helps deal with inversion of control issues.[5] The async block is invoked using the Async.Run
function. Multiple async blocks are executed parallely 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
.[5]
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.
Examples
A few small samples follow:
(* This is a comment *) (* Sample hello world program *) printf "Hello World!"
#light open Microsoft.FSharp.Collection.List (* print a list of numbers recursively *) let rec printlist lst = (* When using "#light", you must indent with 4 spaces *) if lst = [] then () else printf "%d\n" (nth lst 0) printlist (tl lst) (* Same thing, using matching against list elements *) let rec printlist l = match l with | [] -> () | h :: t -> printfn "%A" h printlist t
#light (* Fibonacci Number formula *) let rec fib n = match n with | 0 -> 0 | 1 | 2 -> 1 | n -> (fib (n - 1)) + (fib (n - 2)) (* Print even fibs *) [1 .. 10] |> List.map (fun n -> fib n) |> List.filter (fun n -> (n mod 2) = 0) |> printlist (* Same thing, using Comprehension syntax *) [ for i in 1..10 do let r = fib i if r % 2 = 0 then yield r ] |> printlist
#light (* Sample Windows Forms Program *) (* 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 *) do form.Controls.Add(label) (* Finally, run the form *) do Application.Run(form)
F# is compatible with the XNA Game Studio Express product, which permits construction of games for Windows and for the Xbox 360.
References
- ^ S. Somasegar. "F# - A functional Programming Language". Retrieved 2007-10-18.
- ^ a b c d e f g h i "F# Language Overview" (PDF). Retrieved 2007-12-14.
- ^ "F# from C# and other .NET Languages". Retrieved 2007-12-14.
- ^ a b "Some Details on F# Computation Expressions". Retrieved 2007-12-14.
- ^ a b c "Introducing F# Asynchronous Workflows". Retrieved 2007-12-14.