Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / F#

Fun with F#

1.00/5 (4 votes)
28 Apr 2010CPOL5 min read 1  
Fun with F#F# (pronounced F sharp) is a functional programming language for the .NET Framework that combines the succinct, expressive, and compositional style of functional programming with the runtime, libraries, interoperability, and object model of .NET, that lets users concentrate on...
Fun with F#

F# (pronounced "F sharp") is a functional programming language for the .NET Framework that combines the succinct, expressive, and compositional style of functional programming with the runtime, libraries, interoperability, and object model of .NET, that lets users concentrate on the problems they are solving rather than getting lost in programming details.

Functional programming offers important new ways to think about problem solving. The F# interactive lets developers work interactively with data and application-programming interfaces in a lightweight environment. F# also provides a set of core features for making parallel and asynchronous programming easier.

F#, developed in a partnership between Microsoft Research and the Microsoft Developer Division becomes a first-class language in Visual Studio 2010. Don Syme, inventor of F# and leader of the team, has a different and entirely capricious definition.

" ‘F is for Fun.’ F# enables users to write simple code to solve complex problems. Programming with F# really does make many programming tasks simpler, and our users have consistently reported that they've found using the language enjoyable. A good functional program is like a beautiful poem: You see the pieces of a solution come together."

F# provides new tools for existing Visual Studio developers and extends the reach of Visual Studio to new audiences.

F# which can be used on varied platforms, such as Mac and Linux, in addition to Windows, provides a tool bag of functions from which users can pick to solve their problems. Such languages operate on a higher level, and this abstraction of functionality from coding is a big benefit in certain domains.

The core syntax of F# follows in the tradition of ML programming languages, in particular, OCaml.

F# is a strongly typed language that uses type inference. As a result, data types need not be explicitly declared by the programmer; they will be deduced by the compiler during compilation. However, it also allows explicit data type declaration. F# supports all CLI types and objects. But it extends the type system and categorizes types as immutable types or mutable types. Immutable types are primarily used for functional programming.

F# includes a functional programming component supporting which 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. A 0-tuple has one value only: (), which conveys no information. 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 example was named r).

The list type is a regular linked list represented either using a head::tail notation or a shorthand as [item1; item2; item3]. An empty list is written [].

Constructors are used to create a view of the data type different from the actual implementation. Data types are created with the type keyword. F# uses the let keyword for binding type values to a named variable.

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 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. Being an instance of a type, functions can be passed as arguments to other functions. F# supports lambda functions and closures as well. It also allows function composition using the >> operator. Every statement in F# is a expression with a definite return type. 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. It 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.

F# provides sequence expressions that allows for a defining a sequence block (seq { ... } or [ ... ] or [| ... |]) encapsulating constructs that act on a collection such that the results and another function, such that the function is invoked on the results yielded from the collection. For example, seq { for b in 0 .. 50 do if b < 25 then yield b*b } is a sequence expression that forms a sequence of squares of numbers from 0 to 24 by filtering out numbers from the range of numbers from 0 to 50. The sequence is a lazy evaluation, i. e., the collection is processed and results yielded on-demand. It can be used for filtering. Sequence expressions are generalized as Computation Expressions.

Examples:

/*finds the factorial of n */

let rec factorial n =

match n with

| 0 -> 1

| _ -> n * factorial (n - 1)


/* print the list of numbers */

let rec printList lst =

match lst with

| [] -> ()

| h :: t ->

printf "%d\n" h

printList t

/* finds the Fibonacci series */

let rec fib n =

match n with

| 0 | 1 -> n

| _ -> fib (n - 1) + fib (n - 2)


/* create a window*/

let form = new Form(Visible=true, TopMost=true, Text="Hello World")


/* create a label */


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 label to the form */

form.Controls.Add(label)


/* run the form */

[<STAThread>]

Application.Run(form)


/* primes between m and n */

let primes m n =

seq {m .. n}

|> Seq.map primeAsync

|> Async.Parallel

|> Async.RunSynchronously

|> Array.filter snd

|> Array.map fst

primes 50000 90999

|> Array.iter (printfn "%d")


Happy computing! :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)