{"id":12209,"date":"2014-07-01T12:04:28","date_gmt":"2014-07-01T16:04:28","guid":{"rendered":"http:\/\/blog.xamarin.com\/?p=12209"},"modified":"2014-07-01T12:04:28","modified_gmt":"2014-07-01T16:04:28","slug":"introduction-to-f-with-xamarin","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/introduction-to-f-with-xamarin\/","title":{"rendered":"Introduction to F# with Xamarin"},"content":{"rendered":"<p>\t\t\t\t<a href=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/rachel-reese.png\"><img decoding=\"async\" class=\"size-full wp-image-11330 alignright\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/rachel-reese.png\" alt=\"rachel-reese\" width=\"100\" height=\"100\" \/><\/a><em>Rachel Reese (<a href=\"https:\/\/twitter.com\/rachelreese\">@RachelReese<\/a>) is a long-time software engineer and math geek who recently relocated to Nashville, TN to work at Firefly Logic. Rachel is an ASPInsider and an F# MVP. You can catch her at Xamarin Evolve 2014, where you can <a href=\"https:\/\/evolve.xamarin.com\/\">learn from industry leaders and Xamarin experts<\/a>to advance your projects and career.<\/em><\/p>\n<p><em>This blog post is part of our continuing celebration of F# Week at Xamarin! Celebrate by getting your own <a href=\"\/run-a-f-sharp-app-get-a-f-sharp-shirt\/\">F# t-shirt<\/a>!<\/em><\/p>\n<p><strong>Why F#?<\/strong>\nLet\u2019s first dig into a few of my favorite reasons to consider <a href=\"http:\/\/developer.xamarin.com\/guides\/cross-platform\/fsharp\/fsharp_support_overview\/\" target=\"_blank\">F#<\/a> for your next Xamarin project: type inference, units of measure, type providers, as well as the ever-crucial clarity and conciseness of code.<\/p>\n<p><strong>Type Inference<\/strong>\nPeople often underestimate the benefits of type inference, but the ability to clear out the type definitions from code and concentrate on the code itself, instead of all the clutter around the declaration, is tremendous. Consider this example (from <a href=\"http:\/\/stackoverflow.com\/questions\/196294\/what-is-a-catamorphism-and-can-it-be-implemented-in-c-sharp-3-0\/196451\">here<\/a>, via <a href=\"http:\/\/lorgonblog.wordpress.com\/2009\/10\/25\/overview-of-type-inference-in-f\/\">here<\/a>):<\/p>\n<p>C#:<\/p>\n<pre class=\"lang:csharp decode:true\">\n    public static Tree&lt;KeyValuePair&lt;A, bool&gt;&gt; DiffTree&lt;A&gt;(Tree&lt;A&gt; tree, Tree&lt;A&gt; tree2)\n    {\n        return XFoldTree((A x, Func&lt;Tree&lt;A&gt;, Tree&lt;KeyValuePair&lt;A, bool&gt;&gt;&gt; l, Func&lt;Tree&lt;A&gt;, Tree&lt;KeyValuePair&lt;A, bool&gt;&gt;&gt; r, Tree&lt;A&gt; t) =&gt; (Tree&lt;A&gt; t2) =&gt;\n            Node(new KeyValuePair&lt;A, bool&gt;(t2.Data, object.ReferenceEquals(t, t2)),\n                 l(t2.Left), r(t2.Right)),\n            x =&gt; y =&gt; null, tree)(tree2);\n    }\n<\/pre>\n<p>The equivalent F# is much easier on the eyes. The code itself might still be incomprehensible, but it is at least not drowning in required type definitions. It\u2019s no longer necessary to filter through all the extra information before trying to understand what\u2019s happening.<\/p>\n<pre class=\"lang:fsharp\">\nlet DiffTree(tree,tree2) =\n    XFoldTree (fun x l r t t2 -&gt;\n        let (Node(x2,l2,r2)) = t2\n        Node((x2,t===t2), l l2, r r2)) (fun _ _ -&gt; Leaf) tree tree2\n<\/pre>\n<p>For more information on type inference, see the <a href=\"http:\/\/fsharpforfunandprofit.com\/\">F# for Fun and Profit<\/a> website. There are some fabulous examples of how it works, and how to troubleshoot the errors that sometimes show up.<\/p>\n<p><strong>Units of Measure<\/strong>\nUnits of measure are types that allow one to add unit information to a numeric type in F#. Once a value is tagged with a unit type, it can only be combined with other values that have that same unit. For example, if we want to track distances and times, it\u2019s possible to create:<\/p>\n<pre class=\"lang:fsharp\">\n[&lt;Measure&gt;] type s\n[&lt;Measure&gt;] type m\n<\/pre>\n<p>Then, when we define a new value, we can easily associate our new unit with it:<\/p>\n<pre class=\"lang:fsharp\">\nlet time = 30&lt;s&gt;\nlet distance = 10&lt;m&gt;\n<\/pre>\n<p>The compiler will error if we try to add the two values, but it is possible to divide them:<\/p>\n<pre class=\"lang:fsharp\">\nlet velocity = distance\/time\n<\/pre>\n<p>If we hover over this declaration, the tooltip for this value will show:<\/p>\n<pre class=\"lang:fsharp\">\nval velocity : int&lt;m\/s&gt;\n<\/pre>\n<p>All scientific computing will benefit from enforcing units (game physics!) but it doesn\u2019t have to be exclusively the domain of science. Think about using pixel, USD, or Fahrenheit, among others!<\/p>\n<p>It\u2019s also possible to use generic units of measure in a function. For example, we\u2019d like to calculate a perimeter, given some distances. We can declare the function like so:<\/p>\n<pre class=\"lang:fsharp\">\nlet perimeter = (x:int,&lt;'distance&gt;) (y:int&lt;'distance&gt;) = 2*x + 2*y\n<\/pre>\n<p>In this manner, we\u2019re able to utilize one function for many different units of measure. As long as the units for a single given call are the same, the code will compile. However, the compiler will still throw an error if we try to call perimeter with two different units. To wit:<\/p>\n<pre class=\"lang:fsharp\">\n\/\/ Compiler error: The unit of measure 'ft' does not match the unit of measure 'm'\nlet p_1 = perimeter 10&lt;m&gt; 4&lt;m&gt;\nlet p_2 = perimeter 2&lt;ft&gt; 3&lt;m&gt;\n<\/pre>\n<p><strong>Type Providers<\/strong>\nType providers are a mechanism that allows F# code to access typed information from external data sources with no code generation, all in just a few lines of code. They are a revolution in data access! F# was the first enterprise-grade language to have type providers, and is still the only .NET language to have them. So, if we want to use a type provider in our Xamarin project, we\u2019ll need to use F#!<\/p>\n<p>There are many, many type providers available, but I\u2019ll concentrate on two that are especially useful with Xamarin projects today \u2013 the <a href=\"https:\/\/github.com\/fsprojects\/SQLProvider\">SQLProvider<\/a> and the<a href=\"http:\/\/fsharp.github.io\/FSharp.Data\/\"> Freebase Provider<\/a>.<\/p>\n<p><strong>SQLProvider<\/strong><\/p>\n<p>The SQLProvider provides access to MS SQL Server, SQLite, PostgreSQL, Oracle, MySQL, ODBC, and MS Access databases. Since SQLite is a tremendously common database to hook up with both iOS and Android applications, let\u2019s take a look at what\u2019s required to use the SQLProvider type provider to connect to a SQLite database in an F# Xamarin project!<\/p>\n<p>First, we declare a type. We\u2019ll need to change this to include the connection string, as well as the path to the mono.sqlite.dll.<\/p>\n<pre class=\"lang:fsharp\">\ntype sql = SqlDataProvider\n<\/pre>\n<p>At this point, we\u2019re ready to go. To show off the SQLite provider, let\u2019s build a quick port of the Xamarin Tasky app (see original here). We\u2019ll need to create just a couple of functions for our data layer: GetIncompleteTasks, AddTask, UpdateTask, and DeleteTask. However, first we need to get the data context:<\/p>\n<pre class=\"lang:fsharp\">\nlet ctx = sql.GetDataContext ()\n<\/pre>\n<p>Every time we type `ctx`, we\u2019ll get code completion on the remaining pieces:<\/p>\n<p><a href=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/2014-07-01_1414.png\"><img decoding=\"async\" class=\"wp-image-12224 aligncenter\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/2014-07-01_1414-300x194.png\" alt=\"2014-07-01_1414\" width=\"255\" height=\"165\" \/><\/a><\/p>\n<p>As well as tooltips, which show that the information coming back from SQLite is fully typed:<\/p>\n<p><a href=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/2014-07-01_1415.png\"><img decoding=\"async\" class=\"size-medium wp-image-12225 aligncenter\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/2014-07-01_1415-300x51.png\" alt=\"2014-07-01_1415\" width=\"300\" height=\"51\" \/><\/a><\/p>\n<p>Once we have set up the data context, creating the methods we need is as easy as pie. Let\u2019s declare a type for the return data, to use in our queries:<\/p>\n<pre class=\"lang:fsharp\">\ntype task = { Description : string; mutable Complete : bool; }\n<\/pre>\n<p>Then, to return the incomplete tasks, we use the familiar query syntax:<\/p>\n<pre class=\"lang:fsharp\">\nlet GetIncompleteTasks () =\n    query { for data in ctx.``[main].[tasks]`` do\n                where (data.complete = 0L)\n                select {Description=data.task; Complete = false}}\n            |&gt; Sql.toList\n<\/pre>\n<p>This returns an F# list of tasks, where complete is false. That\u2019s it. No messy ORMs to contend with, no long data access libraries to futz with; we only need a database connection and a query. Adding a task is just as easy, we need to create a new task, update the two fields (&#8220;&lt;-&#8221; is the F# assignment operator), and finally, submit our updates.<\/p>\n<pre class=\"lang:fsharp\">\nlet AddTask description =\n    let newTask = ctx.``[main].[tasks]``.Create()\n    newTask.task &lt;- description\n    newTask.complete &lt;- 0L\n    ctx.SubmitUpdates()\n<\/pre>\n<p><strong>Freebase<\/strong><\/p>\n<p>The Freebase.com web site describes itself as a community-curated database. They currently have a list of nearly 44 million topics, and over 2.5 billion facts. Connecting our app in to all their data is simple, with the Freebase type provider! We merely need to get the context, and start querying.<\/p>\n<p>The Freebase database is especially exciting because the data is returned with additional units of measure. In the example above, when the results are returned, and in the tooltips, we can see that the particle charge is shown in coulombs!<\/p>\n<p><a href=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/2014-07-01_1422.png\"><img decoding=\"async\" class=\"size-medium wp-image-12228 aligncenter\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/2014-07-01_1422-300x91.png\" alt=\"2014-07-01_1422\" width=\"300\" height=\"91\" \/><\/a><\/p>\n<p>As with all type providers, the Freebase provider also has code completion into the structure of our data source. It frees us up to explore the data!<\/p>\n<p><a href=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/2014-07-01_1423.png\"><img decoding=\"async\" class=\"size-medium wp-image-12229 aligncenter\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/2014-07-01_1423-300x189.png\" alt=\"2014-07-01_1423\" width=\"300\" height=\"189\" \/><\/a><\/p>\n<p>Keep an eye out on the Xamarin Blog for Part 2 of Getting Started with Xamarin and F#, where I&#8217;ll discuss using F# to build amazing cross-platform, native apps.<\/p>\n<p>&nbsp;\t\t<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Rachel Reese (@RachelReese) is a long-time software engineer and math geek who recently relocated to Nashville, TN to work at Firefly Logic. Rachel is an ASPInsider and an F# MVP. You can catch her at Xamarin Evolve 2014, where you can learn from industry leaders and Xamarin expertsto advance your projects and career. This blog [&hellip;]<\/p>\n","protected":false},"author":1936,"featured_media":39167,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[4],"class_list":["post-12209","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-xamarin-platform"],"acf":[],"blog_post_summary":"<p>Rachel Reese (@RachelReese) is a long-time software engineer and math geek who recently relocated to Nashville, TN to work at Firefly Logic. Rachel is an ASPInsider and an F# MVP. You can catch her at Xamarin Evolve 2014, where you can learn from industry leaders and Xamarin expertsto advance your projects and career. This blog [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/12209","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/users\/1936"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=12209"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/12209\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media\/39167"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=12209"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=12209"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=12209"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}