Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

F#

F#

Checking the sample code

(Contributed by Djoums):

Looking at the syntax

  • This is very different from an imperative style code! A proper introduction to functional programming (FP) is unfortunately beyond the scope of this playground.
  • Single line comments can be declared with //, but multi-line comments are between (* and *). Don't ask...
  • |> is the pipe forward operator, used to chain the function calls. Each call receives the result of the previous one as a parameter.
  • There are some function names (Convert.ToString and PadLeft) which look exactly the same as in our C# solution. This is not a coincidence. As C#, F# and VB .NET are all targeting Microsoft's Common Language Infrastructure (CLI) on .NET Core, they share some of the standard libraries.
  • Unlike the using statement in C#, F# uses open. This comes from a design choice of organizing functions in modules rather than namespaces.
  • fun x -> defines an anonymous lambda function on the fly.
  • if..then..else is not a conditional statement, but a conditional expression so it returns a result.
  • in is equivalent to a new line after a let, allowing you to write several instructions in one go.

Other characteristics

Collections are usually very important in F#, here are some points worth noting:

  • Lists in F# are very different from their C# counterpart. They are immutable singly-linked lists designed for enumeration, but not for direct indexing (you can, but performance will be horrendous).
  • Arrays are your usual fixed-size contiguous-memory fast access collections. They are not immutable however. Note that we used an array map call in our example with Array.map.
  • Sequences are an abstraction that represents a collection, which doesn't care about how the collection is implemented under the hood. They are also Lazy, making them very similar to IEnumerable in C#. We also used a map call on a sequence in our example, but this time it was with Seq.map.
  • You can of course create your own collections.

F# defines itself as "functional-first" programming language. Unlike Haskell, which is pure uncompromising FP, with F# you can mix in some imperative or object-oriented style in your code, when it makes sense. However, this can be abused. To demonstrate, let us look at an F# Chuck Norris solution in imperative style. Don't try this at home! :-)

Resources to check

Meme

Coming next...

The natural choice for the next section is the "most-FP language of all FP languages", Haskell...

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content