{"id":13775,"date":"2017-07-24T09:50:53","date_gmt":"2017-07-24T16:50:53","guid":{"rendered":"https:\/\/blogs.msdn.microsoft.com\/dotnet\/?p=13775"},"modified":"2019-06-20T20:02:32","modified_gmt":"2019-06-21T03:02:32","slug":"get-started-with-f-as-a-c-developer","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/dotnet\/get-started-with-f-as-a-c-developer\/","title":{"rendered":"Get Started with F# as a C# developer"},"content":{"rendered":"<h2>Get Started with F# as a C# developer<\/h2>\n<p>One of our previous posts, <a href=\"https:\/\/blogs.msdn.microsoft.com\/dotnet\/2017\/05\/31\/why-you-should-use-f\/\">Why You Should Use F#<\/a>, listed a few reasons why F# is worth trying out today.  In this post, we&#8217;ll cover some of the basics you need to know to be successful.  This post is intended for people who are coming from a C#, Java, or other object-oriented background.  The concepts covered here should seem very familiar to existing F# programmers.<\/p>\n<p>This post won&#8217;t make any attempt to show you how to &quot;translate&quot; C# code into F#. This is because C# and F# represent different programming paradigms, which makes each suited to its own purpose. We think you&#8217;ll find that it expands your mind and helps you be a better programmer to learn functional programming concepts.  That value comes to you the fastest if you don&#8217;t think about trying to translate from one paradigm to another.<\/p>\n<p>Now is the time to be curious, inquisitive, and ready to learn brand-new things.  Let&#8217;s get going!<\/p>\n<h2>Immediate differences<\/h2>\n<p>Before we dive into concepts, let&#8217;s look at a small snippet of F# code and see a few areas where F# differs from C#.  Here is some basic F# code with two functions and a printed result:<\/p>\n<p><script src=\"https:\/\/gist.github.com\/cartermp\/052f5a1adcf8287f395b08965f13ca2e.js\"><\/script><\/p>\n<p>Note that there are no type definitions, semicolons, or braces.  The only parentheses are used to call <code>sumOfSquares<\/code> with <code>5<\/code> as input, printing its result.  The pipeline operator (<code>|&gt;<\/code>) is used much like a unix-style pipe.  <code>square<\/code> is a function passed directly as a parameter to the <code>List.map<\/code> function (this is known as first-class functions).<\/p>\n<p>Although there are many more differences we could talk about, there are deeper things going on here, and they are key to understanding F#.<\/p>\n<h2>Mapping core C# concepts to core F# concepts<\/h2>\n<p>The following table provides a basic mapping of some of the core concepts from C# to F#.  It&#8217;s intentionally short and non-exhaustive so that it&#8217;s easy to remember as you begin to learn F#.<\/p>\n<table border=\"1\" cellpadding=\"5\">\n<thead>\n<tr>\n<th>C# and Object-Oriented Programming<\/th>\n<th>F# and Functional Programming<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Variables<\/td>\n<td>Immutable values<\/td>\n<\/tr>\n<tr>\n<td>Statements<\/td>\n<td>Expressions<\/td>\n<\/tr>\n<tr>\n<td>Objects with Methods<\/td>\n<td>Types and functions<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Here&#8217;s a quick primer on some this terminology:<\/p>\n<ul>\n<li>Variables are values which can change in-place, or <em>vary<\/em>.  It&#8217;s in the name!<\/li>\n<li>Immutable values are values which cannot change after they&#8217;re assigned.<\/li>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Statement_(computer_science)\">Statements<\/a> are units of work, performed imperatively, by a running program.<\/li>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Expression_(computer_science)\">Expressions<\/a> are units of code which evaluate to a value.<\/li>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Data_type\">Types<\/a> are classifications of data in a program.<\/li>\n<\/ul>\n<p>It&#8217;s worth noting that everything in the C# column is also possible in F# (and quite easy to accomplish).  There are also things in the F# column which are possible in C#, though they&#8217;re more difficult to accomplish.  It&#8217;s also worth noting that items in the left column are not &quot;bad&quot; for F#, either.  Objects with methods are perfectly valid to use in F#, and can often be the best approach for F# depending on your scenario.<\/p>\n<h2>Immutable values instead of variables<\/h2>\n<p>One of the most transformative concepts in functional programming is immutability.  It&#8217;s often underrated in the functional programming community. But if you&#8217;ve never used a language where immutability is the default behavior, it&#8217;s often the first and biggest hump to get over.  Nearly all functional programming languages have immutability at their core.<\/p>\n<p><script src=\"https:\/\/gist.github.com\/cartermp\/bf13076cd07f8f98fa9c86eb96cb29a2.js\"><\/script><\/p>\n<p>In the previous statement, the value of <code>1<\/code> is <em>bound<\/em> to the name <code>x<\/code>.  <code>x<\/code> now always refers to the value <code>1<\/code> for its lifetime, and cannot be modified.  For example, the following code does not reassign the value of <code>x<\/code>:<\/p>\n<p><script src=\"https:\/\/gist.github.com\/cartermp\/27a9cc4b0a4ba088ace0e4c9f67c64f7.js\"><\/script><\/p>\n<p>Instead, the second line is an equality comparison to see if <code>x<\/code> is equal to <code>x + 1<\/code>.  Although there is a way to mutate <code>x<\/code> by making it <code>mutable<\/code> and using the <code>&lt;-<\/code> operator (see <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/fsharp\/language-reference\/values\/#mutable-variables\">Mutable Variables<\/a> for more), you&#8217;ll quickly find that it&#8217;s easier to think about how to solve problems <em>without<\/em> reassigning values.  This allows you to play to the strengths of F#, rather than treat it as another imperative programming language.<\/p>\n<p>We said that immutability was transformative, and that means that there are some very concrete differences in approaches to solving a problem.  For example, <code>for<\/code> loops and other basic imperative programming operations are not typically used in F#.<\/p>\n<p>As a more concrete example, say you wish to compute the squares of an input list of numbers.  Here is an approach to that in F#:<\/p>\n<p><script src=\"https:\/\/gist.github.com\/cartermp\/1fb1b41d47283f4ae68008a793a930d2.js\"><\/script><\/p>\n<p>Notice that there isn&#8217;t a <code>for<\/code> loop to be seen.  At a conceptual level, this is very different from imperative code.  We&#8217;re not squaring each item in the list.  We are mapping the <code>square<\/code> function over the input list to product a list of squared values.  This distinction is subtle in concept, but in practice it can lead to dramatically different code.  For starters, <code>getSquares<\/code> actually produces a whole other list.<\/p>\n<p>Immutability does more than just change the way you manipulate data in lists.  The concept of <a href=\"http:\/\/wiki.c2.com\/?ReferentialTransparency\">Referential Transparency<\/a> will come naturally in F#, and it is a driver in how systems are built and pieces of that system are composed.  Execution characteristics of a system become more predictable, because values cannot change when you didn&#8217;t anticipate them to change.<\/p>\n<p>Furthermore, when values are immutable, concurrent programming becomes simpler.  Because values cannot be changed due to immutability, some of the more difficult concurrency problems you can encounter in C# are not a concern in F#.  Although the use of F# does not magically solve all concurrency problems, it can make things easier.<\/p>\n<h2>Expressions instead of statements<\/h2>\n<p>As mentioned earlier, F# makes use of <em>expressions<\/em>.  This is in contrast with C#, which uses <em>statements<\/em> for nearly everything.  The difference between the two can initially seem subtle, but there is one thing to always keep in mind: an expression produces a value.  Statements do not.<\/p>\n<p><script src=\"https:\/\/gist.github.com\/cartermp\/7445813491e586b39d7bb55616138398.js\"><\/script><\/p>\n<p>In the previous code sample, you can see a few things which are very different from imperative languages like C#:<\/p>\n<ul>\n<li><code><a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/fsharp\/language-reference\/conditional-expressions-if-then-else\">if...then...else<\/a><\/code> is an expression, not a statement.<\/li>\n<li>Each branch of the <code>if<\/code> expression produces a value, which in this case is the return value of the <code>getMessage<\/code> function.<\/li>\n<li>Each invocation of <code>getMessage<\/code> is an expression which takes a string and produces a string.<\/li>\n<\/ul>\n<p>Although this is very different from C#, you&#8217;ll most likely find that it feels natural when writing code in F#.<\/p>\n<p>Diving a bit deeper, F# actually uses expressions to model statements.  These return the <a href=\"https:\/\/docs.microsoft.com\/dotnet\/fsharp\/language-reference\/unit-type\"><code>unit<\/code><\/a> type.  <code>unit<\/code> is roughly analogous to <code>void<\/code> in C#:<\/p>\n<p><script src=\"https:\/\/gist.github.com\/cartermp\/8876d6511d3364dc02cb54b7b83ab900.js\"><\/script><\/p>\n<p>In the previous sample <code>for<\/code> expression, everything is of type <code>unit<\/code>.  Unit expressions are expressions which return no value.<\/p>\n<h2>F# arrays, lists, and sequences<\/h2>\n<p>The previous code samples have used F# arrays and lists.  This section explains them a bit more.<\/p>\n<p>F# comes with a few collection types, and the most commonly used ones are arrays, lists, and sequences.<\/p>\n<ul>\n<li><a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/fsharp\/language-reference\/arrays\">F# arrays<\/a> are .NET arrays.  They are mutable, which means that their values can be changed in-place.  They are evaluated eagerly.<\/li>\n<li><a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/fsharp\/language-reference\/lists\">F# lists<\/a> are immutable singly-linked lists.  They can be used to form <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/fsharp\/language-reference\/pattern-matching#list-pattern\">list patterns<\/a> with <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/fsharp\/language-reference\/pattern-matching\">F# pattern matching<\/a>.  They are evaluated eagerly.<\/li>\n<li><a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/fsharp\/language-reference\/sequences\">F# sequences<\/a> are immutable <code>IEnumerable&lt;T&gt;<\/code>s under the covers.  They are evaluated lazily.<\/li>\n<\/ul>\n<p>F# arrays, lists, and sequences also have array, list, and sequence expression syntax.  This is very convenient for different scenarios where you can generate one of these collections programmatically.<\/p>\n<p><script src=\"https:\/\/gist.github.com\/cartermp\/920aadb60d66e511ceb969c97b54a629.js\"><\/script><\/p>\n<h3>Mapping common LINQ methods to F# functions<\/h3>\n<p>If you are familiar with LINQ methods, the following table should help you understand analogous functions in F#.<\/p>\n<table border=\"1\" cellpadding=\"5\">\n<thead>\n<tr>\n<th>LINQ<\/th>\n<th>F# function<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td><code>Where<\/code><\/td>\n<td><code>filter<\/code><\/td>\n<\/tr>\n<tr>\n<td><code>Select<\/code><\/td>\n<td><code>map<\/code><\/td>\n<\/tr>\n<tr>\n<td><code>GroupBy<\/code><\/td>\n<td><code>groupBy<\/code><\/td>\n<\/tr>\n<tr>\n<td><code>SelectMany<\/code><\/td>\n<td><code>collect<\/code><\/td>\n<\/tr>\n<tr>\n<td><code>Aggregate<\/code><\/td>\n<td><code>fold<\/code> or <code>reduce<\/code><\/td>\n<\/tr>\n<tr>\n<td><code>Sum<\/code><\/td>\n<td><code>sum<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>You&#8217;ll also notice that the same set of functions exist for the <code>Seq<\/code> module, <code>List<\/code> module, and <code>Array<\/code> module.  The <code>Seq<\/code> module functions can be used on F# sequences, lists, or arrays.  The array and list functions can only be used on F# arrays and F# lists, respectively.  Additionally, F# sequences are lazy, whereas F# lists and arrays use eager evaluation.  Using <code>Seq<\/code> functions on an F# list or F# array will incur lazy evaluation, and the type will then be an F# sequence.<\/p>\n<p>Although the previous paragraph may be a lot to unpack, it should feel intuitive as you write more F#.<\/p>\n<h2>Functional pipelines<\/h2>\n<p>You may have noticed the <code>|&gt;<\/code> used in previous code samples.  This operator is very similar to unix pipes: it takes something on the left-hand side, and makes that the input to something on the right.  This operator (called &quot;pipe&quot;, or &quot;pipeline&quot;) is used to form a <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/fsharp\/language-reference\/functions\/index#function-composition-and-pipelining\">functional pipeline<\/a>.  Here&#8217;s an example:<\/p>\n<p><script src=\"https:\/\/gist.github.com\/cartermp\/4d9511811c3da41ef8ca2aecc1b71744.js\"><\/script><\/p>\n<p>Walking through this code sample, <code>items<\/code> is passed as input to the <code>Seq.filer<\/code> function.  The output of <code>Seq.filter<\/code>, a sequence, is then passed as input to the <code>Seq.map<\/code> function.  The output of <code>Seq.map<\/code> is the output of <code>getOddSquares<\/code>.<\/p>\n<p>Use of the pipeline operator is so much fun to use that it&#8217;s rare to see F# code which <em>doesn&#8217;t<\/em> make use of it.  It&#8217;s usually near the top of everyone&#8217;s favorite F# feature list!<\/p>\n<h2>F# Types<\/h2>\n<p>Because F# is a .NET language, it shares the same primitive types that C# does: <code>string<\/code>, <code>int<\/code>, etc.  It also has .NET objects, and supports the four main pillars of object-oriented programming.  It also has <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/fsharp\/language-reference\/tuples\">tuples<\/a>.  F# also has two primary types not found in C#: <a href=\"https:\/\/docs.microsoft.com\/dotnet\/fsharp\/language-reference\/records\">Records<\/a> and <a href=\"https:\/\/docs.microsoft.com\/dotnet\/fsharp\/language-reference\/discriminated-unions\">Discriminated Unions<\/a>.<\/p>\n<p>A <a href=\"https:\/\/docs.microsoft.com\/dotnet\/fsharp\/language-reference\/records\">Record<\/a> is a named, ordered grouping of values which have equality baked in.  And by equality, we mean in the most literal sense.  There is no need to distinguish between reference equality or some custom definition of value equality between two objects.  Records are values, and values have equality.  They are Product Types for the category theorists out there.  They have a number of uses, but one of the most obvious ones is a replacement for POCOs or POJOs.<\/p>\n<p><script src=\"https:\/\/gist.github.com\/cartermp\/9e4ee775057ff1490f45e773549e8cbf.js\"><\/script><\/p>\n<p>The other foundational F# type is a <a href=\"https:\/\/docs.microsoft.com\/dotnet\/fsharp\/language-reference\/discriminated-unions\">Discriminated Union, or DU<\/a>.  DUs are a type which could be one of a number of named cases.  These are Sum Types for the category theorists out there.  They can also be recursively-defined, which dramatically simplifies hierarchical data.<\/p>\n<p><script src=\"https:\/\/gist.github.com\/cartermp\/7a7c381e5812508c9fc5c6536da16dd2.js\"><\/script><\/p>\n<p>Ta-da!  Armed with the power of Discriminated Unions and F#, you can pass any programming interview which requires you to flip a binary search tree.<\/p>\n<p>You may have noticed a bit of funky syntax in the <code>Node<\/code> case of the tree definition.  This is actually a type signature for a tuple.  That means that a BST, as we&#8217;ve defined it, can either be empty, or a tuple of <code>(value, left subtree, right subtree)<\/code>.  Read more about <a href=\"https:\/\/fsharpforfunandprofit.com\/posts\/function-signatures\/\">Signatures<\/a> to learn more.<\/p>\n<h2>Putting it all together: F# Syntax in 60 seconds<\/h2>\n<p>The following snippet of code is presented with permission from <a href=\"https:\/\/twitter.com\/ScottWlaschin\">Scott Wlaschin<\/a>, an F# community hero who wrote the following great overview of F# syntax.  You should be able to read through in about a minute.  It has been edited slightly.<\/p>\n<p><script src=\"https:\/\/gist.github.com\/cartermp\/90604331f83cdd45e04ad1736f3ae6f6.js\"><\/script><\/p>\n<p>Additionally, there is the <a href=\"https:\/\/docs.microsoft.com\/dotnet\/fsharp\/tour\">Tour of F#<\/a> document in our official documentation for .NET and its languages.<\/p>\n<h2>What you can do next<\/h2>\n<p>This post covered a lot of things, but it only began to scratch the surface of F#.  We hope that after reading this post, you&#8217;ll be able to dive further into F# and functional programming.  Here are a few things we recommend building as a way to learn F# even further:<\/p>\n<ul>\n<li>Use F# to build <a href=\"https:\/\/github.com\/sfsharp\/dojo-fractal-forest\">beautiful fractal trees<\/a>.<\/li>\n<li>Use F# to explore and analyze <a href=\"https:\/\/www.kaggle.com\/wcukierski\/the-simpsons-by-the-data\">data on The Simpsons<\/a> inside <a href=\"https:\/\/notebooks.azure.com\/\">Azure Notebooks<\/a>.<\/li>\n<li>Use F# and <a href=\"https:\/\/suave.io\/\">Suave<\/a> to build <a href=\"https:\/\/theimowski.gitbooks.io\/suave-music-store\/content\/en\/\">a web app<\/a>.<\/li>\n<li>Use F# to build a serverless app or component with <a href=\"https:\/\/docs.microsoft.com\/azure\/azure-functions\/functions-reference-fsharp\">Azure Functions<\/a>.<\/li>\n<\/ul>\n<p>There are many, many more things you can use F# for, so the previous list is by no means exhaustive.  F# is used from things as simple as <a href=\"https:\/\/www.hanselman.com\/blog\/ExploringFAKEAnFBuildSystemForAllOfNET.aspx\">a build script<\/a> to forming the backend of a <a href=\"https:\/\/tech.jet.com\/blog\/tag\/f\/\">a billion-dollar eCommerce site<\/a>.  There is no shortage of projects you can use F# for.<\/p>\n<h2>Additional resources<\/h2>\n<p>It&#8217;s worth noting that there is also a wealth of information about learning F#, including from a C# or Java background.  The following links will be helpful as you dive deeper into learning F#:<\/p>\n<ul>\n<li><a href=\"https:\/\/docs.microsoft.com\/dotnet\/fsharp\/\">F# Guide<\/a><\/li>\n<li><a href=\"https:\/\/swlaschin.gitbooks.io\/fsharpforfunandprofit\/content\/\">F# for Fun and Profit<\/a><\/li>\n<li><a href=\"https:\/\/en.wikibooks.org\/wiki\/F_Sharp_Programming\">F# Wiki<\/a><\/li>\n<li><a href=\"https:\/\/learnxinyminutes.com\/docs\/fsharp\/\">Learn X in Y Minutes: F#<\/a><\/li>\n<\/ul>\n<p>There are also multiple documented ways to <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/fsharp\/get-started\/\">get started with F#<\/a>.<\/p>\n<p>Finally, the F# community is incredibly welcoming for beginners.  There is a very active slack run by the F# Software Foundation, with rooms for beginners, which you can access by <a href=\"http:\/\/foundation.fsharp.org\/join\">joining for free<\/a>.  We highly encourage you to do so!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Get Started with F# as a C# developer One of our previous posts, Why You Should Use F#, listed a few reasons why F# is worth trying out today. In this post, we&#8217;ll cover some of the basics you need to know to be successful. This post is intended for people who are coming from [&hellip;]<\/p>\n","protected":false},"author":678,"featured_media":58792,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[685,196,197,636,646],"tags":[],"class_list":["post-13775","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-dotnet","category-dotnet-core","category-aspnet","category-fsharp","category-visual-studio"],"acf":[],"blog_post_summary":"<p>Get Started with F# as a C# developer One of our previous posts, Why You Should Use F#, listed a few reasons why F# is worth trying out today. In this post, we&#8217;ll cover some of the basics you need to know to be successful. This post is intended for people who are coming from [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts\/13775","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/users\/678"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/comments?post=13775"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts\/13775\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/media\/58792"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/media?parent=13775"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/categories?post=13775"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/tags?post=13775"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}