layout: page
title: “Why use F#?”
description: “Why you should consider using F# for your next project”
nav: why-use-fsharp
hasIcons: 1

image: “/assets/img/four-concepts2.png”

Although F# is great for specialist areas such as scientific or data analysis, it is also an excellent choice for enterprise development.
Here are five good reasons why you should consider using F# for your next project.

Conciseness" class="reference-link">“Why use F#?” in one page - 图6 Conciseness

F# is not cluttered up with coding “noise” such as curly brackets, semicolons and so on.

You almost never have to specify the type of an object, thanks to a powerful type inference system.

And, compared with C#, it generally takes fewer lines of code to solve the same problem.

  1. // one-liners
  2. [1..100] |> List.sum |> printfn "sum=%d"
  3. // no curly braces, semicolons or parentheses
  4. let square x = x * x
  5. let sq = square 42
  6. // simple types in one line
  7. type Person = {First:string; Last:string}
  8. // complex types in a few lines
  9. type Employee =
  10. | Worker of Person
  11. | Manager of Employee list
  12. // type inference
  13. let jdoe = {First="John";Last="Doe"}
  14. let worker = Worker jdoe

Convenience" class="reference-link">“Why use F#?” in one page - 图7 Convenience

Many common programming tasks are much simpler in F#. This includes things like creating and using
complex type definitions, doing list processing,
comparison and equality, state machines, and much more.

And because functions are first class objects, it is very easy to create powerful and reusable code by creating functions
that have other functions as parameters,
or that combine existing functions to create new functionality.

  1. // automatic equality and comparison
  2. type Person = {First:string; Last:string}
  3. let person1 = {First="john"; Last="Doe"}
  4. let person2 = {First="john"; Last="Doe"}
  5. printfn "Equal? %A" (person1 = person2)
  6. // easy IDisposable logic with "use" keyword
  7. use reader = new StreamReader(..)
  8. // easy composition of functions
  9. let add2times3 = (+) 2 >> (*) 3
  10. let result = add2times3 5

Correctness" class="reference-link">“Why use F#?” in one page - 图8 Correctness

F# has a powerful type system which prevents many common errors such
as null reference exceptions.

Values are immutable by default, which prevents a large class of errors.

In addition, you can often encode business logic using the type system itself in such a way
that it is actually impossible to write incorrect code
or mix up units of measure, greatly reducing the need for unit tests.

  1. // strict type checking
  2. printfn "print string %s" 123 //compile error
  3. // all values immutable by default
  4. person1.First <- "new name" //assignment error
  5. // never have to check for nulls
  6. let makeNewString str =
  7. //str can always be appended to safely
  8. let newString = str + " new!"
  9. newString
  10. // embed business logic into types
  11. emptyShoppingCart.remove // compile error!
  12. // units of measure
  13. let distance = 10<m> + 10<ft> // error!

Concurrency" class="reference-link">“Why use F#?” in one page - 图9 Concurrency

F# has a number of built-in libraries to help when more than one thing at a time is happening.
Asynchronous programming is very easy, as is parallelism.

F# also has a built-in actor model, and excellent support for event handling
and functional reactive programming.

And of course, because data structures are immutable by default, sharing state and avoiding locks is much easier.

  1. // easy async logic with "async" keyword
  2. let! result = async {something}
  3. // easy parallelism
  4. Async.Parallel [ for i in 0..40 ->
  5. async { return fib(i) } ]
  6. // message queues
  7. MailboxProcessor.Start(fun inbox-> async{
  8. let! msg = inbox.Receive()
  9. printfn "message is: %s" msg
  10. })

Completeness" class="reference-link">“Why use F#?” in one page - 图10 Completeness

Although it is a functional language at heart, F# does support other styles which are not 100% pure,
which makes it much easier to interact with the non-pure world of web sites, databases, other applications, and so on.

In particular, F# is designed as a hybrid functional/OO language, so it can do virtually everything that C# can do.

Of course, F# is part of the .NET ecosystem, which gives you seamless access to all the third party .NET libraries and tools.
It runs on most platforms, including Linux and smart phones (via Mono and the new .NET Core).

Finally, it is well integrated with Visual Studio (Windows) and Xamarin (Mac), which means you get a great IDE with IntelliSense support, a debugger,
and many plug-ins for unit tests, source control, and other development tasks. Or on Linux, you can use the MonoDevelop IDE instead.

  1. // impure code when needed
  2. let mutable counter = 0
  3. // create C# compatible classes and interfaces
  4. type IEnumerator<'a> =
  5. abstract member Current : 'a
  6. abstract MoveNext : unit -> bool
  7. // extension methods
  8. type System.Int32 with
  9. member this.IsEven = this % 2 = 0
  10. let i=20
  11. if i.IsEven then printfn "'%i' is even" i
  12. // UI code
  13. open System.Windows.Forms
  14. let form = new Form(Width= 400, Height = 300,
  15. Visible = true, Text = "Hello World")
  16. form.TopMost <- true
  17. form.Click.Add (fun args-> printfn "clicked!")
  18. form.Show()

The “Why Use F#?” series

The following series of posts demonstrates each of these F# benefits, using standalone snippets of F# code (and often with C# code for comparison).