fsharpdevelopment

In today’s F# session I’ll examine a sample program. It helps to be inspired and learn more about real-life usage and capabilities of the language.

It’s definitely a fun game if nothing else and offers a lot to learn for F# noobs like myself!

Make Santa Jump

One thing to pay attention is when you first clone and build it gives compile errors.

Build error

To fix this you have reload the solution and restart Visual Studio.

Notes

  • use keyword has the same functionality as a let binding but adds a call to Dispose method. It’s like the using statement
  • open keyword is similar to using in C# but it can be used for other modules as well as namespaces
  • I added a source file called Game.fs and started getting the following error:

Files in libraries or multiple-file applications must begin with a namespace or module declaration, e.g. ‘namespace SomeNamespace.SubNamespace’ or ‘module SomeNamespace.SomeModule’. Only the last source file of an application may omit such a declaration.

Even though G came before P, Visual Studio didn’t automatically reorder files alphabetically like it would normally do with C#. Apparently even the order of files are important in F# (who knew?). There are even Move Up/Down options in the context menu. So I right-clicked Program.fs and moved it down so it would be the last source file in the project and it fixed the build error!

  • Properties can be defined with get and set members as below:
module Game

type Suit = 
    | Hearts 
    | Clubs 
    | Diamonds 
    | Spades

type Card(suit : Suit, value : int) = 
    let mutable faceValue = value

    member this.Value
        with get() = faceValue
        and set(value) = faceValue <- value

Resources

fsharpdevelopment

It’s about time for me to develop some application to put the basics in use. I will develop it in Visual Studio so first is to get accustomed to using F# in VS 2013. There are 5 project types for F#:

  • Console Application
  • Library
  • Tutorial
  • Portable Library
  • Portable Library (Legacy)

Portable Library should be helpful when developing universal Windows Store apps. For my purposes Console Application and Library should be enough. Before going any further I decided to check out the Tutorial project. So below are today’s notes on using F# in VS 2013 and from the tutorial project

Notes

  • Tutorial project comes with a single Tutorial.fsx file with all the sample code. Console Application, on the other hand, comes with Program.fs. Apparently an fsx is the extension for F# script files: “An F# script file is a normal F# source code file, except that .fsx files have a few extra capabilities.”.

fsx Windows Explorer integration

  • Ctrl + Alt + F combination opens the F# Interactive Window
  • You can select a code block and run it in the interactive window by right-clikcing and selecting “Execute in Interactive” or using Alt + Enter shortcut.
  • A module is a logical grouping of related code segments. The code in a module must be indented. When types and functions are inside modules they can be accessed by their fully-qualified names from outside the module:
module MyModule1 =
    let module1Value = 100
    let module1Function x =
        x + 10

module MyModule2 =
    let module2Value = 121
    let module2Function x =
        x * (MyModule1.module1Function module2Value)

MyModule2.module2Function 5
  • Modules can have public, private or internal access modifiers. The default is public.
  • A foreach loop can be defined as for i in {values} -> … For example
let sampleTableOfSquares = [ for i in 0 .. 99 -> (i, i*i) ]
  • When defining functions parenthesis can be used optionally. I think this makes the function look more “mathy” and a littler easier to read.
let func1a (x) = x*x + 3             
  • To improve the readability further it sounds like a good idea to annotate the type always (even when it can be inferred automatically)
let func2 (x:int) = 2*x*x - x/5 + 3   
  • Boolean operations are straightforward
let boolean1 = true
let boolean2 = false
let boolean3 = not boolean1 && (boolean2 || false)
printfn "The expression 'not boolean1 && (boolean2 || false)' is %A" boolean3
  • Double-quotes can be used inside strings be enclosing them with triple quotes
let string4 = """He said "hello world" after you did"""
  • A fragment of a string can be accessed by this notation:
let string1 = "Hello"
let string2  = "world"
let helloWorld = string1 + " " + string2
let substring = helloWorld.[0..6]
  • A tuples is a set of ordered values
let tuple1 = (1, "fred", 3.1415)
  • Lists can be defined in various syntax
let list1 = [ ]
let list2 = [ 1; 2; 3 ]
let list3 = 42 :: list2
let numberList = [ 1 .. 1000 ]
let squares = 
    numberList 
    |> List.map (fun x -> x*x) 
  • Classes can be defined by type keyword
type Vector2D(dx : float, dy : float) = 
    let length = sqrt (dx*dx + dy*dy)
    member this.DX = dx  
    member this.DY = dy
    member this.Length = length
    member this.Scale(k) = Vector2D(k * this.DX, k * this.DY)
  • Generics classes are supported
type StateTracker<'T>(initialElement: 'T) = 
    let mutable states = [ initialElement ]
  • Classes can implement interfaces
type ReadFile() =
    let file = new System.IO.StreamReader("readme.txt")
    member this.ReadLine() = file.ReadLine()
    interface System.IDisposable with    
        member this.Dispose() = file.Close()
  • Arrays use a similar syntax to lists except [ ] operators are used
let array1 = [| 1 .. 1000 |]
let evenNumbers = Array.init 1001 (fun n -> n * 2) 
  • Sequences are evaluated on-demand and are re-evaluated each time they are iterated. They are defined by curly braces
let numbersSeq = seq { 1 .. 1000 }
  • Recursive functions are defined by let rec keyword
let rec factorial n = 
    if n = 0 then 1 else n * factorial (n-1)
  • Record types can be created by type keyword and curly braces
type ContactCard = 
    { Name     : string;
      Phone    : string;
      Verified : bool }
  • Union types can be created by type keyword and pipe-separated values
type Suit = 
    | Hearts 
    | Clubs 
    | Diamonds 
    | Spades
  • Option values are any kind of value tagged with either ‘Some’ or ‘None’.
  • Code can be annotated with units of measure when using F# arithmetic over numeric types
    open Microsoft.FSharp.Data.UnitSystems.SI.UnitNames

    [<Measure>]
    type mile =
        /// Conversion factor mile to meter: meter is defined in SI.UnitNames
        static member asMeter = 1600.<meter/mile>
  • Large arrays can be processed in parallel
    let oneBigArray = [| 0 .. 100000 |]
    
    // do some CPU intensive computation 
    let rec computeSomeFunction x = 
        if x <= 2 then 1 
        else computeSomeFunction (x - 1) + computeSomeFunction (x - 2)
       
    // Do a parallel map over a large input array
    let computeResults() = oneBigArray |> Array.Parallel.map (fun x -> computeSomeFunction (x % 20))

    printfn "Parallel computation results: %A" (computeResults())
  • Events are also supported
    open System

    // create instance of Event object that consists of subscription point (event.Publish) and event trigger (event.Trigger)
    let simpleEvent = new Event<int>() 

    // add handler
    simpleEvent.Publish.Add(
        fun x -> printfn "this is handler was added with Publish.Add: %d" x)

    // trigger event
    simpleEvent.Trigger(5)

Conclusion

I like the tutorial script that came with VS. It shows all basic aspects in one place. I think I’ve spent enough time covering the basics. I need to dive deeper and develop something on my own or at least check out complete applications which I’m going to do next.

Resources

gadgetreview

To be brutally honest I didn’t need this device when I bought it. I had started considering of buying one and, as usually I do, just ended up buying it just because it’s a shiny little toy that got my attention!

Since I forked over £1350 quids I had to justify it to myself to be able to sleep at nights. And my justification is that now that I have a fully mobile device I can work outside home quite often. In coffee shops, pubs and even in parks come spring. I think changing venues every now and then is a good idea to increase productivity and motivation. The main benefit of this device is that it’s running the exact OS my desktop is running meaning that I can use the exact same development environment on the go. I already had a 17” laptop which, in theory, allowed me to do that but it was a 5kg unwieldy beast with only 3-hour battery life so in practice it’s doomed to stay at home or office.

Laptop vs. tablet

First impressions

Another driving factor behind my decision was since it’s also a tablet I could use it as a comic book reader and it’s indeed a great reader. Compared to my good ol’ iPad 2 it provides a much better experience.

Performance-wise it’s working great so far. The model I got has an Intel Core i7 CPU with 8GB RAM and 256GB SSD which is close to my desktop. The desktop has 32GB RAM but it runs a lot of virtual machines so 8GB with no-VMs sucking a ton of memory is good enough for a decent development machine.

Tips, Pros and cons

  • Tip: Toggle function keys: Fn button + Caps Lock. Fn keys are used much more frequently than searching or changing screen brightness.
  • Pro: Lovely and crisp 12” screen with 2160 x 1440 resolution. Great for reading comic books.
  • Pro: Good performance for development
  • Pro: Type-cover feels sturdy with strong magnets
  • Con: Appears connected to network while it’s not after waking up from sleep (I guess it’s a Windows flaw rather than Surface)
  • Con: Only 1 USB port is generally not good enough especially when it’s generally occupied by the mouse
  • Con: The type-cover keyboard feels a bit flimsy at times. But still it’s good enough to write code and blogposts.
  • Con: Gets hot sometimes

Conclusion

All in all, I’m glad I bought this device. Once I manage to forget the price tag I’m sure I’ll enjoy it even more! The 12” screen is great for comic books and it becomes a full-blown development machine with the type-cover attached. People criticize the battery life but I think it’s adequate for a work laptop (at least compared to my Asus my laptop it lasts forever.

I’m writing this post in a coffee shop and I guess I’ll be around town more often and still be able to write code while travelling around :-)

Resources