January 30, 2012 10:03pm
Fundamental functional techniques

It has been awhile since I posted something on F#, but I have been busy reading part 2 of Real-World Functional Programming. This so far has been one of the harder chapters. Not because I couldn’t understand what is going on in the examples it was more of a mind shift I didn’t quite yet grasp fully. Most of the examples were very easy to follow however the sheer functional aspect of the examples made me realize I am not thinking functionally quite yet, hopefully I will be soon. As usual here are some random notes and blurbs that stood out for me while reading this section.

Chapter 5, Using functional values locally

  • In F#, if you need to recognize that a type either contains a value or does not, you can use the ‘option’ type. When working with the option type you never have the danger of dealing with a NullReferenceException since by definition an option type always is something either a value or missing a value.
  • Values are typically used to solve problems in functional programming
  • Data is usually something large and used by multiple portions of your program
  • A type specifies an entire domain of values and a value is always an element within a domain specified by its type.
  • Returning multiple values from a function is the primary motivation behind using tuples
  • You can use out parameters in F# as you do in C#, however tuples is generally preferred, because of that .net method that utilize out parameters expose a method that returns tuples let (success, parsed) = Int32.TryParse("42")
  • When using tuples always consider the complexity of the tuple you are creating
  • A tuple can contain more than two elements however if you begin to use 3+ elements in your tuple consider creating a record type for greater readability and maintainability
  • Discriminated unions provides support for values that can be a number of named cases
  • When doing pattern matching on Discriminated unions you are required to write all possible matches since the value passed into the function is unknown.
  • You can declare a variable with let bindings twice, this practice is known as hiding a value
  • The pattern matching construct in F# is similar to the switch statement in C#
  • In F# null is rarely used, most times when you encounter null it means you are working with other aspects of the .net framework, in F# the use of the option type is preferred
  • When using the option type in F# you are forced to write the match when a value is undefined
  • The option type is similar to Nullable<T> as in C#
  • F# type inference allows for the creation of function that use generics automatically
  • F# filter is to C# where linq extension method, they both take a predicate function
  • In C# you create lambda expression and in F# it is a lambda function
  • A function is called a pure function if it behaves in a mathematical way, a function that returns true for even numbers for example
  • The F# lambda expression starts with the fun keyword, you specify multiple arguments with spaces, you do not have to specify the type explicitly.
  • In C# you can not use the var keyword when creating lambda expressions since the compiler needs to know if it is a Func or an Expression

Chapter 6, Processing values using higher-order functions

  • Higher order functions are very important to functional programming
  • You can create custom operators in F# using the normal let binding as you do with functions. You can use any F# mathematical character or logical operators and other special characters ($%.?&^~!), you can also use * however care needs to be taken since that is also used for a multi-line comment
  • When creating custom operators you can use infix (takes two parameters) notation when using the operator, “A” +> “B” +> “C”
  • You can also create prefix operators (takes one parameter) you need to start the operator with either ~ or !
  • Use of the |> operator allows you to write the argument on the left hand side of the call, this is very similar to the idea of calling C# extension methods where the variable is on the left as well
  • If you wrap an operator inside of () this allows you to call the operator as you would a function. 2 + 2 using () would look like (+) 2 2
  • One of the most important types in F# is the option type
  • Option.map transforms a given option type into another option type specified by the mapping function supplied
  • Understanding a behavior of a function using only the type is a very important skill of a functional programmer
  • option.bind invokes a function that takes an option type that also returns an option type
  • You can compose functions together by using the » operator
    let function1 x = x + 1
    let function2 x = x * 2
    let h = function1 >> function2
    let result5 = h 100
    
    Example from MSDN, the result is 202 (100 + 1 * 2)
  • In F# if you want to do SelectMany the corresponding function is List.collect

Chapter 7, Designing data-centric programs

  • When desiging a functional program, first think about the data that the program works with.
  • When a record type in F# is simly a labeled tuple
  • When declaring a record type you have to specify the types of the fields and their names
  • When creating a record type you do not need to specify the type of the record since the F# compiler will infer the type based upon the fields
  • A record is a functional data structure which also means it is immutable as well
  • F# allows you to create new record types easily by using the with keyword, this allows you to create the new record type and only specify the fields the are changing, F# will copy the rest automatically
  • The hole in the middle pattern allows you create a generic function that takes a function which gets executed in the middle. The hole is the function you supply to the other function that has pre and post logic.
  • The .net IEnumerable<T> is abbreviated as seq<’a> in F#.
  • Seq.head is the same Linq extension method .First()
  • Code example from chapter 7

Chapter 8, Designing behavior-centric programs

  • One frequent requirement for behavior-centric programs is the ability to load new behaviors dynamically from a library
  • Since functions are treated as values you can easily create a list of functions to run on some type
  • Storing functions in a list easily allow you to add and remove these behaviors
  • Point free programming style allows you to define functions that do not directly specify the argument names, I do not exactly understand this yet but the wikipedia article sort of explains it
  • Point-free style should be used only when the intent is very clear since removing the arguments from the definition could make the code harder to read and maintain
  • The strategy pattern is useful whent he application needs to choose several algorithms at run time
  • The command pattern describes a way to represent actions in an application, when using the command patter you most likely will need to work with mutable state. Since functional programming relies on immutable state when using the command pattern you should document clearly where the mutable portions are located.
  • Closures allow you to limit the scope of mutable state when developing functional programs
  • A function isn’t just code it also is a closure
  • You can create mutable values by using the ref keyword
  • C# variables are mutable by default so when using closures be very careful, an example would be a for loop creating a closure over a variable which ends up being the last value in the last iteration for all closures
  • If you use a let binding followed by an and this allows both bindings to see each other

Next up in the book is advanced F# topics, I have a feeling tackling functional programming in one month might end up being a pipe dream. Learning the syntax is easy altering your mindset is hard.

January 19, 2012 9:49pm
Real-World Functional Programming, Part 1 (Chapter 4)

Chapter 4 was actually quite fun! This chapter goes through a simple application that reads data from a csv file and produces a pie chart. The chapter starts off using the F# interactive console all the way to creating a F# application that creates a simple GUI.

Some notes while building the application
  • By the use of pattern matching you can create generic functions. In C# you need to specify the function as generic but by the use of pattern matching F# will create functions that are automatically generalized. see calculateSum
  • F# does not insert automatic conversions between numeric types as in C#, you need to directly use int(), float(), etc.
  • You can use pattern matching the in for in construct like

for (title, value) in data do

  • You can use the built in sprintf or String.Format to format strings, if you can use the built in F# method it is usually preferable to do so.
  • Make sure you read the book when typing up the examples in Visual Studio, I was banging my head against the desk for 10-15 minutes until I realized it was RectangleF not Rectangle
  • module Module1
    
    open System
    open System.Drawing
    open System.Windows.Forms
    open System.IO
    
    
    let convertDataRow(csvLine:string) =
        let cells = List.ofSeq(csvLine.Split(',')) //creates a list where the first first 
    
    //element is the name and the last is a number
        match cells with //do a pattern match on the list
        | title :: number :: _ -> //match the tuple that has a first element a next/last element and any other elements are ignored
            let parsedNumber = Int32.Parse(number) //parse the first element value
            (title, parsedNumber) //create a new tuple that is of type string and int
        | _ -> failwith "Incorrect data format!"
    
    
    let rec processLines(lines) =
        match lines with //do a pattern match on the lines
        | [] -> [] //if the line is empty do nothing
        | currentLine :: remaining -> // if the lines are not empty, 
    
    //grab the first element into currentLine and the remaining lines into that variable
            let parsedLine = convertDataRow(currentLine) //parse the line into a tuple (string, int)
            let parsedRest = processLines(remaining) //rec call the processLines function with the rest of the lines remaining
            parsedLine :: parsedRest //build a list of all the parsed lines.
    
    
    
    let rec calculateSum(rows) =
        match rows with
        | [] -> 0
        | (_, value) :: tail ->
            let remainingSum = calculateSum(tail)
            value + remainingSum
    
    let mainForm = new Form(Width = 620, Height = 450, Text = "Pie Chart") //same way of doing 
    
    //var mainForm = new Form {Width = 620};
    
    let menu = new ToolStrip()
    
    let openButton = new ToolStripButton("Open")
    let saveButton = new ToolStripButton("Save", Enabled = false) //same way of 
    
    //doing var saveButton = new ToolStripButton("Save") { Enabled = false};
    
    ignore(menu.Items.Add(openButton)) //calling menu.Items.Add() returns the index of the added element, to make sure the result 
    
    //is ignored by F# use ignore()
    ignore(menu.Items.Add(saveButton)) //this takes any return value and makes it return unit (void)
    
    let boxChart =
        new PictureBox
            (BackColor = Color.White, Dock = DockStyle.Fill,
            SizeMode = PictureBoxSizeMode.CenterImage)
    
    mainForm.Controls.Add(menu)
    mainForm.Controls.Add(boxChart)
    
    let random = new Random()
    let randomBrush() =
        let r,g,b = random.Next(256), random.Next(256), random.Next(256)
        new SolidBrush(Color.FromArgb(r,g,b))
    
    let drawPieSegment(gr:Graphics, title, startAngle, occupiedAngle) =
        let brush = randomBrush()
        gr.FillPie(brush, 170, 70, 260, 260, startAngle, occupiedAngle)
        brush.Dispose()
    
    let font = new Font("Times New Roman", 11.0f)
    
    let centerX, centerY = 300.0, 200.0
    let labelDistance = 150.0
    
    let drawLabel (graphics:Graphics, title, startAngle, angle) =
        let labelAngle = float(startAngle + angle/2)
        let ra = Math.PI * 2.0 * labelAngle  / 360.0
        let x = centerX + labelDistance * cos(ra)
        let y = centerY + labelDistance * sin(ra)
        let size = graphics.MeasureString(title, font)
        let xPoint = float32(x) - size.Width / 2.0f
        let yPoint = float32(y) - size.Height / 2.0f
        let rc = new PointF(xPoint, yPoint)
        
        let boundingBox = new RectangleF(rc, size)
        graphics.DrawString(title, font, Brushes.Black, boundingBox)
    
    let drawStep(drawingFunction, graphics:Graphics, sum, data) =
        let rec drawStepUntil(data, angleSoFar) =
            match data with
            | [] -> () //returns unit ie void
            | [title, value] -> //only matches a tuple of tile, value with no tail element
                let angle = 360 - angleSoFar
                drawingFunction(graphics, title, angleSoFar, angle)
            | (title, value) :: tail -> //matches a tuple head of title/value WITH a tail element(s)
                let angle = int(float(value) / sum * 360.0)
                drawingFunction(graphics, title, angleSoFar, angle)
                drawStepUntil(tail, angleSoFar + angle)
        drawStepUntil(data, 0)
    
    
    let drawChart(file) =
        let lines = List.ofSeq(File.ReadAllLines(file))
        let data = processLines(lines)
        let sum = float(calculateSum(data))
    
        let pieChart = new Bitmap(600, 400)
        let graphics = Graphics.FromImage(pieChart)
        graphics.Clear(Color.White)
        drawStep(drawPieSegment, graphics, sum, data)
        drawStep(drawLabel, graphics, sum, data)
    
        graphics.Dispose()
        pieChart
    
    let openAndDrawChart(e) =
        let dialog = new OpenFileDialog(Filter="CSV Files|*.csv")
        if(dialog.ShowDialog() = DialogResult.OK) then
            let pieChart = drawChart(dialog.FileName)
            boxChart.Image <- pieChart
            saveButton.Enabled <- true
    let saveDrawing(e) =
        let dialog = new SaveFileDialog(Filter="PNG Files|*.png")
        if(dialog.ShowDialog() = DialogResult.OK) then
            boxChart.Image.Save(dialog.FileName)
    
    //TODO: Drawing ofthe chart and UI
    [<STAThread>]
    do
        openButton.Click.Add(openAndDrawChart)
        saveButton.Click.Add(saveDrawing)
        Application.Run(mainForm)

    I will say as exciting as this application was to produce I am still struggling with the way you create applications. I am very curious what is the best practice when you start to create separate modules for your applications. Right now everything is a function, which makes sense but looking at the code you have one file with just a bunch of functions! (I guess i am still thinking in the O-O style mindset.

    January 19, 2012 9:32pm
    Real-World Functional Programming, Part 1

    Well after a few days I finally was able to finish Part 1 of the book Real-World Functional Programming.  So far I am really enjoying this book.

    Like my other posts about F#, I am going to share a few snip its of things I learned while reading the first section. This will hopefully reinforce the knowledge I picked up.

    Chapter 1 - Thinking differently

    • Functional programming is the Evaluation of expressions at it’s core.
    • The next section describes how functional programming came into existence starting with LISP and these functional programming ideas came to spawn F# in the .net framework.
    • The next section was by far the biggest eye opener with immutable and mutable data types. This simple fact of striving for immutable data types allows for greater safety when dealing with concurrency. This idea also lends itself greatly with the ability to parallelize portions of your code.
    • One of the key benefits of using F# is you are granted the power of the functional space with the richness of the O-O .net framework.
    • If you are using Linq, you already have some of the concepts needed to think functionally. Since Linq uses declarative style coding, where you tell what you want the computer to do but not how to do it.
    • Linq isn’t the only declarative style in the .net stack, XAML is declarative as well
    • The declarative nature also lends well with compositionally. This allows you to reuse functions and queries in other parts of your system to build up higher order functions or queries.
    • Any variable in F# is immutable by default. The only way to create a mutable type is to specifically declare it.
    • Using F# is very easy to use inside of Visual Studio 2010, built into the IDE you can quickly and easily create complex F# functions and constructs using the F# interactive mode. This mode is like a console window which allows you to type in any F# syntax.
    • F# can offer C# developers two main advantages. The first is the ability to use the F# interactive mode for rapid development of ideas and algorithms without the need to create a new console application or project. Since F# is .net you can create modules and assemblies you can reference in your existing C# applications.

    Chapter 2 - Core concepts in functional programming

    • The start of this capture goes down to the roots of some of the functional concepts notably lambda calculus.
    • Once again the book talks more about immutable data types, (it almost appears they really want you to learn this concept!)
    • Functions are like values and can be passed around to other functions to build higher order functions
    • F# uses type inference to figure out parameters and return values from functions. This allows you to remove the need for decorating your code with type annotations. With that being said you can supply these type annotations in your F# functions in case the compiler can not figure out the type or to increase readability of your code.
    • C# has a very pseudo version of type inference with the var keyword. However it mostly is syntactical sugar. var myNumber = 0; The var keyword can only be used in statements and not in parameters of methods.
    • Pattern matching is everywhere in F# and can be applied numerous places. You can use pattern matching to match tuples in a list to decompose the pieces and even in for in loops to decompose the same list into tuple values. This concept of pattern matching is very powerful in recursive functions.
    • Units of measure this is by far one of simplest concepts but very powerful about F#.
      
      let maxSpeed = 50.0<km/h>
      let yourSpeed = 50.0<mile/h>
      
      
      Both of these types are floats, however they have different units of measure. If you try to supply a function with variables that are different units of measure you will get compile time errors. This simple concept allows you to limit yourself from some simple mathematical mistakes by not applying the proper conversion to change the unit of measure to the appropriate value.

    Chapter 3 - Meet tuples, lists, and functions in F# and C#

    • let bindings can only be used after they are declared
    • If you want to create explicit scoping of let bindings you can use the let in () syntax
      
      let number = 21 in
      (
      	printfn "%d" number
      )
      
      
      This allows you to declare a scope for the binding of number. If you every use the let in syntax you are required to supply a body for the expression.
    • The default action for the F# compiler is to use line breaks and indentation to figure out the expressions in your application (and insert ;). You can however use () and ; in your application if it helps increase readability and maintainability.
    • All functions have a corresponding function signature which describes the parameters and return type of a function.
      
      	let calc number1 number2 = number1 * number2
      	//signature (param1, param2, result) calc : int -> int -> int
      
      
      This is similar to the Func type signature
      
      	Func<int,int,int> calc = (number1, number2) -> number1 * number2;
      
      
    • All values in F# are immutable by default, if you need to declare a mutable value you need to declare the binding as such, let mutable number = 42
    • When writing F# applications try to have EVERY value immutable trying to stay strict to this idea will keep with the style of functional programming.
    • Tuples are used quite a bit in F# application, these are also immutable by default. Creating tuples is very easy, let person = ("Mark", 99)
    • You can use pattern matching with tuples by simply using the match keyword.
      
      let doMatch newItem2 theTuple =
      	match theTuple with
      	| (firstItemInTheTuple, _) -> (firstItemInTheTuple, newItem2) //decomposes the tuple by matching the first
      
      
      //item and uses the _ as a catch all for the other item (ignore it)
      
      
    • Lists are also immutable, we can create lists easily but they can not be modified after they are created. If you wish to adjust a list you need to decompose the list and create a new list from the source list. Modifying a list in F# is impossible. This list is not to be confused with the generic List(T) in the .net framework
    • You can also do pattern matching on lists similarly to how you match tuples.
      
      match theList with
      | [] -> //matches an empty list.
      | head :: tail -> //a list with a head element and the tail (the rest of the list).
      
      
      When you do pattern matching on a list and you do not include all possible matches, you will be treated with a compiler warning. Your code will still function but if you pass in a list which matches your missing pattern match the application will produce an exception.
    • If you need to pass in a function to a function you can declare the function signature as you would with types.
      
      let specialFunction (functionToPassIn: int->int) param2 =
      
      

    So far the first three chapters were quite good and very helpful in learning the core concepts about F#. Just the idea of thinking with immutable data types started to make me rethink ways I developed applications in the past. Next in chapter 4 will include a real world example of how you can develop a simple GUI application that reads in data from a csv file.

    January 11, 2012 7:55pm
    F# and The Imperative World

    The next section in tryfsharp.org is about the imperative world. This section was the one that so far was the easiest to grasp since lots of the concepts were very familiar to me. Mutable variables, reference cells, arrays, loops, records, and collections.

    Notes

    • Mutable Variables
      You can declare a variable binding as mutable by using the mutable keyword. This allows you to reassign the variables by the use of the <- operator.
      let mutable x = 1
      printfn "x=%d" x
      
      x <- 2
      printfn "x=%d" x
      
    • function arguments can not be treated as mutable.
    • If a variable is captured by a closure it can not be mutated in the function.
      let innerUpdate() =
        let mutable i = 1
        let update() =
          i <- 2 * i
      
    • Ref
      You can create reference cells which are independent to any particular function. You declare a binding to a reference cell by using the ‘ref’ keyword. When you need to access the value you can either use ‘!’ or ‘.Value’
      let a = 3.14
      let p = ref a
      printfn "a=%f p=%f" a !p
      printfn "a=%f p=%f" a p.Value
      
      if you need to update the value of a reference cell variable you need to use the ‘:=’ operator. You can also pass reference cell variables into a function as well by using the ‘ref’ keyword in the function definition.
    • Arrays
      Instead of using lists in your functional program you also have access to arrays which allows direct access to elements. You create arrays similar to lists, but prepend and append a | in the variable binding.
      let numbers = [| 1;2;3;4;5;6;7;8;9 |]
      
      You can access elements of an array via a 0 based index with .[] syntax
      let first = numbers.[0]
      
      Each element in an array is considered mutable and can be altered by the same <- syntax.
    • You can slice a portion of an array by using the ‘array.[..]’ syntax.
      let start = number.[2..4]
      
    • You can perform pattern matching on an array by using the match keyword.
      let xIsLessThanY input =
        match input  with
        | [| x; y |] -> x < y
        | _ -> false
      
    • F# contains many helper functions that allow you to work with arrays easier.
      • Array.zeroCreate 20, creates an array of 20 elements of 0
      • let theCopy = Array.copy original, copies an array to another variable.
      • let filteredArray = Array.filter(fun e -> e > 10) unfilteredArray, takes a predicate function and filters an Array.
      • let sumOfTheArray = Array.sum theArray, sums all the elements of an array.
      You can find a complete list of methods in the array module on msdn.
    • Loops
      Two sample looping mechanism in F# are while true do, for, and for in.
      let mutable count = 0
      while count < 10 do
          printfn "Loop Count: %d" count
          count <- count + 1
      
         
      for i = 1 to 10 do
        printfn "Loop #%d" i
      
      for i in [1 .. 10] do
        printfn "Loop #%d" i
      
       
      for i = 10 downto 1 do
        printfn "Loop #%d" i
      
      let vowels = [ 'a'; 'e'; 'i'; 'o'; 'u' ]
      for v in vowels do
        printfn "Loop #%c" v
      
    • Mutable Records
      Mutable records are like defining a class as you would in C# to create a class.
      type Customer =
          {
              Name: string;
              mutable OrderCount: int;
          }
      
      let customer = {Name = "Mark"; OrderCount= 0}
      
      let addOrder (customer: Customer) = 
          customer.OrderCount <- customer.OrderCount + 1
          printfn "Name: %s has an OrderCount of %d" customer.Name customer.OrderCount
      
      addOrder (customer)
      
    • Mutable Collections
      Since F# is part of the .net framework F# also gains access to all of the typical collection types, List<T>, HashSet<T>, Dictionary<K,V>
    • The syntax for creating a list is very similar to how you define a new list in C#.
      open System.Collections.Generic
      
      let listOfBeerStyles = new List()
      listOfBeerStyles.Add("IPA")
      listOfBeerStyles.Add("Pale Ale")
      
      printfn "List: %A" listOfBeerStyles 
      

    January 9, 2012 8:22pm
    The Functional World

    Continuing on with my journey in F# tonight I went through the next section in tryfsharp.org called “The Functional World”. Like usual here are some random notes on the section.

    • If you want to define what the return type should be in an F# function use a : and the return type.
      let sqr (x : float) : float = x * x
      			
      This is usually a good practice to over annotate the code to allow for a better form of self documenting code so the reader does not need to infer what actual parameter types and return types.
    • if-then-else statements in F# are actually called if expressions where the expression will evaluate to either true or false.
      let printYes (x : float) : string = 
          if x >= 10.0 then "yes" else "no"
      
      let good = printYes(10.0)
      
    • If you need to create a recursive function you need to add the keyword “rec” in front of the function definition. This allows for added safety so you do not accidentally create a recursive function. This keyword will also allow for the function to be accessible internally to the function.
      let rec factorial (n : int) =
          if n = 0 then
              1
          else
              n * factorial (n-1)
      
      
    • You can guard against infinite recursion in a function by defining an assert which stops the function from creating a stack overflow exception.
      let rec power (x : float) (n : int) =
          assert (n >= 0)
          if n = 0 then
              1.0
          else
              x * power x (n-1)
      
      Instead of calling the assert you could throw an exception if the parameters are outside of bounds.
      let rec power (x : float) (n : int) =
          if n 
      
    • Arrays are not part of the functional programming paradigm (but they can be used). Instead lists are commonly used instead.
    • Lists are very efficient at adding to the front from a list and creating and conversely at removing an item from the front of a list.
    • You can retrive the head of a list by calling List.head list
      let list = ['h';'e';'l'; 'l'; 'o']
      let head = List.head list
      
      To obtain the tail you can use List.tail
      let list = ['h';'e';'l'; 'l'; 'o']
      let tail = List.tail list
      
    • The F# list library contains additional helper functions to work with list for example you can use List.exists to see if a given list contains a given element.
      let found = List.exists (fun element -> element = 'l') list
      
    • You can use pattern matching on list to help find elements in a list.
      let rec contains list element =
          match list with
          | []       ->   false
          | head :: rest  ->  if head = element then true else contains rest element
      
      let foundByContains = contains list 'h'
      
      Here the :: operator helps to decompose the list to the head element and rest which contains the tail element and the other elements.
    • Functions which accept functional arguments and or return new functions are known as higher order functions. Some examples of these functions are:
      • List.map - which executes a function on each element in a list.
      • List.filter - filters a list of elements which match the given function predicate
      • List.reduce - applies the a given function to the first two elements that result is than passed to the third element and that result is applied to the fourth and so on.
      • List.fold - applies a function to each element in a list but also passes along a variable along which is called the accumulator.
        let data = [("Cats",4);
                    ("Dogs",5);
                    ("Mice",3);
                    ("Elephants",2)]
        let count = List.fold (fun accumulator (animalType, numberOfAnimals) -> accumulator + numberOfAnimals) 0 data
        printfn "Total number of animals: %d" count
        
        Example was from msdn with revised names to make sense.

    So far F# is looking good, I am slowly starting to understand the syntax. The lack of () {} is the hardest part for me to grasp. Next up on the list is the “Imperative World”

    January 5, 2012 8:37pm
    Random F# Knowledge gained today

    Today I started going through the tutorial for F# on www.tryfsharp.org. So far this tutorial is excellent and lets you quickly try F#. The site uses a silverlight plugin which allows you to run F# code in your browser without any IDE. You are up and running within seconds. So far I managed to go through the first section which covers the basics of F#. I will admit some of the constructs so far are nice, not needing to use type annotations because of type inference and the clean syntax of the language (not needing {}, ;, etc). The only complaint so far in the tutorial is with the variable names, they are short and hard to wrap my head around (especially in the currying examples). Anyways here are some random notes I took while going through the first section. Some of this stuff is sort of basic, however typing it up will hopefully make it stick.

    • let statements are not assignment statements. Each let statement creates a new association between a name and a value. In functional programming, such an association is called a binding.
    • In F# indentation matters when writing code there is no termination character such as a ; to terminate a line.  Also there is no {} characters used if/else blocks as in C#.
      C#
      if(x < 5){
          Console.WriteLine("< 5");
      }
      
      F#
      if x < 5
           printfn "< 5"
      
    • There is no void return type in F#, instead the return type would be unit.
    • tuple

      A tuple is similar to a struct in C#, you can define them with any number of named values, however they should be kept fairly small. You can access the values of a tuple by either fst (first value of a tuple) or snd (second value of a tuple)
      let computer = ("iMac", "i7")
      let name = fst computer
      let cpu =  snd computer
      
      Where name contains “iMac” and cpu contains “i7”
    • tuples can not be modified, if you need to alter the values contained in a tuple you need to create a mutable type.
    • Lists

      Lists must contain the same type of values. Each item in a list is separated by ;
      let languages = ["C#"; "F#"; "JavaScript"]
      
    • You can create lists of number with the the “..” operator. let oneToTen = [1 .. 10] will create a list of numbers 1-10, however if you supply two “..” you can specify the number to increment the value. let plusTen = [1 .. 10 .. 100] (e.g. 1, 11, 21, 31…91)
    • Lists are 0 based and if you need to access an element of a list you simply use the [] syntax, with the previous example let number = plusTen.[3] will bind 31 to number;
    • If you want to add an element to the start of a list use :: let newList = -10 :: plusTen
    • If you need to join two lists together use the “@” operator, let myList = plusTen @ newList, this should be used only when needed since it can be expensive depending on the size of the list. You cannot alter an element inside of the list natively, however you can write a function that would allow this to happen by copying the contents and creating a new list. A list is immutable
    • Operators

      F# has the typical arithmetic operators, boolean operators, and comparison operators. One notable operator that is unique to F# is the compare operator.
      let x = 1
      let y = 2
      let lessThan compare x y //returns -1
      
      let x = 1
      let y = 2
      let lessThan compare y x //returns 1
      
      let x = 1
      let y = 1
      let lessThan compare y x //returns 0
      
    • Implicit type conversations do not happen automatically.
      let sum = 29 + 3.5 // does not compile
      
      If you need to provide an explicit conversion for this addition to occur.
      let sum = float 29 + 3.5 //works
      
    • There are a few built in implicit conversions in F# between types.
      • sbyte converts to a signed byte
      • byte converts to an unsigned byte
      • int16 converts to a 16-bit signed integer
      • uint16 converts to a 16-bit unsigned integer
      • int or int32 converts to a 32 bit signed integer
      • uint or uint32 converts to a 32 bit unsigned integer)
      • int64 converts to a 64 bit signed integer
      • uint64 converts to a 64 bit unsigned integer
      • float converts to a double precision float
      • float32 converts to a single precision float
      • decimal converts to a decimal number
      • string converts to a string
      • char converts to a unicode character
    • F# is a statically typed language, and type mismatches will be uncovered by the compiler.
    • Type annotations are not required in F# like in C#. F# achieves this by using type interference to determine what that actual type is in the application. Because of this type interference it is possible that the compiler might choose the wrong type as a parameter or return value. This especially occurs when dealing with + and * calculations. If you are not sure you can easily add the type names to make sure your method has the proper signature of float instead of the potential inferred type of int.
    • Functions are first class objects and can be passed around and even used a parameters in another functions.
    • Being able to pass functions around is essential for predicates passed into List methods such as exists, filter, map, reduce, fold.
    • F# allows for function currying which allows you to create new functions based upon other functions.
      let add a b = a + b
      let addn n = add n
      let f = addn 7
      // What is printed by the following line of code?
      printfn "Value of f 3 = %A" (f 3)
      
      What happens here is that you call function f with a parameter 3 it calls addn 7, addn then calls add n which then unravels to 3 + 7. I think I follow this, but not sure if I can describe it completely just yet.
    • Namespaces and modules

      To use another namespace in your F# program you use open System (similar to C#’s using System;)

    Items accomplished

    • Read wikipedia
    • ordered a book

    January 4, 2012 7:11pm
    Language for January F# (1/12)

    Today I met with our little group that is joining me on the journey on learning twelve programming languages in twelve months in the year 2012. We collectively decided to learn F# as our head first dive into our challenge.

    Why F#?

    Well to be honest the decision was more out of convenience, we all are .net developers running Visual Studio 2010, have all the frameworks installed, and have the given tools needed to get started with little or no effort. Given we are already in January coming off a holiday this seemed like the logical choice.

    What is F#?

    I will not go into to much detail about F# since everything you might want to know is located on wikipedia. So far all I know is that F# is a language that supports three major programming styles. F# is functional programming, imperative programming, and object-oriented programming.

    The next step

    • Read the wikipedia page
    • Find a good book to start learning F#, maybe this one.
    • Go through the tutorials on www.tryfsharp.org. (run F# in your browser with silverlight)
    • Decide on a project to build.

    Until next time…

    printfn "Hello World, from my first F# program"

    January 3, 2012 7:50pm
    Start of a new year

    Well a new year has started and people make new year’s resolutions and this year I plan on learning 12 new languages/topics this year that are outside of my comfort zone which is primarily C# web development.

    Why am I doing this?

    I have been developing with VB/VB.NET and C# for the past 8 ½ years and it is a time for something to change up routine.  I love C# and .Net, but I am overdue to take a look at how other developers solve problems with all of these other languages I hear about on StackOverflow and twitter.  I am in my box and I am comfortable but being a developer and being comfortable is probably one of the worst things you can do.  It is time to shock my system and see what all the fuss is about with F#, why I would want to use Python, and many others.  I hope this will gain me some perspective on how .NET is awesome or “wow .NET is not all that it is cracked up to be for creating my web application”.

    What languages will I learn? *rough draft

    • PHP
    • Java/JSP
    • Ruby on Rails
    • Perl/Mod Perl
    • F#
    • Python
    • Node.js
    • CppCMS (C++ Web Development Framework)
    • Objective-C
    • Haskell
    • Power Shell Scripting
    • Scheme

    Now I know not all of these are languages, some are frameworks for a language.  Still the concept is the same, how on earth do you use C++ to build a web site?  If i want to use a Node.js binding to access a MySql database how on earth is that accomplished.

    The Format

    • Create a specification that will be built in the language of the month
    • How to setup your machine
      • What do you need to install?
      • What do you use as an IDE?
      • Any configuration settings?
    • Was I able to create an application that fulfilled the requirement?
    • What libraries did I use if any?
    • How did I like it? Was it fun to develop in this language?

    It begins

    Well that is it for now, wish me luck and next time you hear from me I hopefully picked a language and what I plan on building.

    Liked posts on Tumblr: More liked posts »