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 
    

  1. markcoleman posted this
Blog comments powered by Disqus