Loading…

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

Like this presentation? Why not share!

Highlights of F# lightning talk

on

  • 1,184 views

 

Statistics

Views

Total Views
1,184
Views on SlideShare
1,184
Embed Views
0

Actions

Likes
0
Downloads
9
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • F# heritage. Robin won the Turing Award in 1991, in part for creating ML. His other contributions were in automated theorem proving and what eventually became the pi calculus.
  • On the left is valid MIPS machine code to load a value into a register. C# has closures and type inference.

Highlights of F# lightning talk Highlights of F# lightning talk Presentation Transcript

  • Some F# Highlights
    Matt Harrington
    http://blog.mbharrington.org
    mbh.work@gmail.com
    @mh415
  • Dealing With Concurrency
    Hire an expert, or …
    Software Transactional Memory, or …
    Functional Programming.
    -Unknown (to me)
  • Features
    Multiparadigm: FP, OO, imperative
    Managed runtime
    Statically typed
    Immutable by default
    Eager evaluation by default
    Impure – allows side effects
  • Free, as in beer & speech
    Open source & cross-platform
    Apache 2.0 license
    Syntax highlighting for TextMate, vim, emacs, TextPad, jedit, and others.
    Free IDEs:
    MonoDevelop
    SharpDevelop
    Visual Studio Shell
  • Robin Milner
    University of Edinburgh
    ML – 1970s
    Don Syme
    MSR Cambridge
    F# - 2002
    Xavier Leroy, et al.
    INRIA, France
    Ocaml - 1996
  • Where is it used?
    Windows x64 driver verification
    adCenter
    Halo 3 – Xbox live
    Amyris
    Credit Suisse
    WebSharper
    Avalda – F# to FPGA
    F# itself
  • Source: http://vslab.codeplex.com
  • FP buzzwords
    • Monads
    • Asynchronous programming
    • Pipeline operator |>
    • Curried by default
    • Continuations
    • Memoization
    • Lazy evaluation
    First class functions
    Immutability
    Recursion
    Type inference
    Pattern matching
    Lists, sequences, tuples, records, discriminated unions
    Optiontype
  • OO
    Classes
    Inheritance
    Extension methods
    Interfaces
    Structs
    Properties
    Delegates
    Enums
    Mutability: let mutable n = 5
  • Totally subjective beta slide
    100101
    00011
    01000
    00000
    00001
    000100
    Scala
    Haskell
    Java
    λ
    F#
    C#
    Not to scale!
  • Taming Asynchronous I/O
    Slide Credit:
    Don Syme
    using System;
    using System.IO;
    using System.Threading;
     
    public class BulkImageProcAsync
    {
        public const String ImageBaseName = "tmpImage-";
        public const intnumImages = 200;
        public const intnumPixels = 512 * 512;
     
        // ProcessImage has a simple O(N) loop, and you can vary the number
        // of times you repeat that loop to make the application more CPU-
        // bound or more IO-bound.
        public static intprocessImageRepeats = 20;
     
        // Threads must decrement NumImagesToFinish, and protect
        // their access to it through a mutex.
        public static intNumImagesToFinish = numImages;
        public static Object[] NumImagesMutex = new Object[0];
        // WaitObject is signalled when all image processing is done.
        public static Object[] WaitObject = new Object[0];
        public class ImageStateObject
        {
            public byte[] pixels;
            public intimageNum;
            public FileStreamfs;
        }
     
     
        public static void ReadInImageCallback(IAsyncResultasyncResult)
        {
            ImageStateObject state = (ImageStateObject)asyncResult.AsyncState;
            Stream stream = state.fs;
            intbytesRead = stream.EndRead(asyncResult);
            if (bytesRead != numPixels)
                throw new Exception(String.Format
                    ("In ReadInImageCallback, got the wrong number of " +
                    "bytes from the image: {0}.", bytesRead));
            ProcessImage(state.pixels, state.imageNum);
            stream.Close();
     
            // Now write out the image. 
            // Using asynchronous I/O here appears not to be best practice.
            // It ends up swamping the threadpool, because the threadpool
            // threads are blocked on I/O requests that were just queued to
            // the threadpool.
            FileStreamfs = new FileStream(ImageBaseName + state.imageNum +
                ".done", FileMode.Create, FileAccess.Write, FileShare.None,
                4096, false);
            fs.Write(state.pixels, 0, numPixels);
            fs.Close();
     
            // This application model uses too much memory.
            // Releasing memory as soon as possible is a good idea,
            // especially global state.
            state.pixels = null;
            fs = null;
            // Record that an image is finished now.
            lock (NumImagesMutex)
            {
                NumImagesToFinish--;
                if (NumImagesToFinish == 0)
                {
                    Monitor.Enter(WaitObject);
                    Monitor.Pulse(WaitObject);
                    Monitor.Exit(WaitObject);
                }
            }
        }
     
           public static void ProcessImagesInBulk()
        {
            Console.WriteLine("Processing images...  ");
            long t0 = Environment.TickCount;
            NumImagesToFinish = numImages;
            AsyncCallbackreadImageCallback = new
                AsyncCallback(ReadInImageCallback);
            for (inti = 0; i < numImages; i++)
            {
                ImageStateObject state = new ImageStateObject();
                state.pixels = new byte[numPixels];
                state.imageNum = i;
                // Very large items are read only once, so you can make the
                // buffer on the FileStream very small to save memory.
                FileStreamfs = new FileStream(ImageBaseName + i + ".tmp",
                    FileMode.Open, FileAccess.Read, FileShare.Read, 1, true);
                state.fs = fs;
                fs.BeginRead(state.pixels, 0, numPixels, readImageCallback,
                    state);
            }
     
            // Determine whether all images are done being processed. 
            // If not, block until all are finished.
            boolmustBlock = false;
            lock (NumImagesMutex)
            {
                if (NumImagesToFinish > 0)
                    mustBlock = true;
            }
            if (mustBlock)
            {
                Console.WriteLine("All worker threads are queued. " +
                    " Blocking until they complete. numLeft: {0}",
                    NumImagesToFinish);
                Monitor.Enter(WaitObject);
                Monitor.Wait(WaitObject);
                Monitor.Exit(WaitObject);
            }
            long t1 = Environment.TickCount;
            Console.WriteLine("Total time processing images: {0}ms",
                (t1 - t0));
        }
    }
    let ProcessImageAsync () =
    async { let inStream = File.OpenRead(sprintf "Image%d.tmp" i)
    let! pixels = inStream.ReadAsync(numPixels)
    let pixels' = TransformImage(pixels,i)
    let outStream = File.OpenWrite(sprintf "Image%d.done" i)
    do! outStream.WriteAsync(pixels') }
     
    let ProcessImagesAsyncWorkflow() =
    Async.Run (Async.Parallel
    [ for i in 1 .. numImages -> ProcessImageAsynci ])
     
    Processing 200 images in parallel
    Equivalent F#, more robust
  • Tail Call Optimization
    .method public static int32 g(int32 x) cil managed
    {
    .maxstack 5
    L_0000: nop
    L_0001: ldarg.0
    L_0002: ldc.i4.0
    L_0003: ble.s L_0007
    L_0005: br.s L_0009
    L_0007: br.s L_0019
    L_0009: newobj instance void Program/g@9::.ctor()
    L_000e: ldarg.0
    L_000f: ldc.i4.1
    L_0010: sub
    L_0011: tail
    L_0013: call int32 Program::f(class [FSharp.Core]Microsoft.<snip>)
    L_0018: ret
    L_0019: ldarg.0
    L_001a: ret
    }
  • Discriminated Unions
    typeNucleotide =
    | Adenine
    | Guanine
    | Tyrosine
    | Cytosine
  • Discriminated Unions (cont.)
    typeBinaryTree =
    | Node ofint * BinaryTree* BinaryTree
    | Empty
    2
    1
    4
    3
    5
    From "Programming F#" by Chris Smith, p. 72
  • Units of Measure
    [<Measure>]
    type kilogram
    letbowlingBall = 7.26<kilogram>
    let force (mass : float<kilogram>) = mass * 9.8
  • Pipeline operator |>
    let numbers = [1 .. 100]
    let square x = x * x
    letsumOfSquares =
    numbers |> List.mapsquare
    |> List.sum
  • Euler Problem #7
    let isPrimenum =
    letupperDivisor = int32(sqrt(float num))
    matchnumwith
    | 0 | 1 -> false
    | 2 -> true
    | n ->seq { 2 .. upperDivisor } |>
    Seq.forall(fun x ->num % x <> 0)
    let primes = Seq.initInfinite id |> Seq.filterisPrime
    let nthPrime n = Seq.nth n primes
    printfn "The 10001st prime number is %i."
    <| nthPrime 10000
    num |> float |> sqrt |> int
    Code from "Juliet" on http://stackoverflow.com/questions/3251957.
  • More…
    Matt Harrington: mbh.work@gmail.com,@mh415, blog.mbharrington.org
    SFsharp.org
    Luca Bolognese’s video (see links on SFsharp.org)
    Programming F# by Chris Smith