KEMBAR78
London F-Sharp User Group : Don Syme on F# - 09/09/2010 | PPTX
A Taste of F# TodayDon Syme, Principal ResearcherMicrosoft Research, Cambridge
Which talk?
Which talk?
Which talk?
Agenda
F# is…a programminglanguage…
F# is…...a programming language that allows you to write simple codeto solve complex problems.
F# is…...a productive, supported, functionalprogramming language that allows you to write simple codeto solve complex problems.
Why is F# appealing in …
Why is F# appealing in finance?
Why is F# appealing in finance?A great fit for much financial work“Programmatic modelling” A typed, efficient scripting language goes a long wayPlays differently for different roles:Enables quants to contribute componentsEnables architects to explore hard problemsEnables developers to tackle parallel and async
Crossing boundariesPerformance +Professional  Development“Programming”“Financial engineering”C++C#JavaF#“QF modelling”Dynamic Domain SpecificProgrammingExpressivity for Mathematical tasks
F# FundamentalsSuccinct, Expressive, Functional Language Parallel, Explorative, Data-rich, AlgorithmicIndustry/Platform-Leading Note: F# is not a replacement for C#/VB/C++ Augments and builds on .NET as multi-lang platform
Why Functional?
Simplicity
Parallel
Simplicity
using System;namespace ConsoleApplication1{class Program{static string greeting= "hello"static void Main(string[] args){Console.WriteLine(greeting);            }}}open Systemlet greeting = "hello"Console.WriteLine(greeting)Simplicity: ScriptingC#F#
Simplicity: Functions as Values   abstract class Command    {      public virtual void Execute();    }    abstract class RoverCommand: Command    {     protected Rover Rover { get; private set; }      public RoverCommand(MarsRoverrover)      {        this.Rover = rover;      }    }    class BreakCommand: RoverCommand    {      public BreakCommand(Rover rover)          : base(rover)      {      }       public override void Execute()      {          Rover.Rotate(-5.0);      }  }  class TurnLeftCommand : RoverCommand  {      public TurnLeftCommand(Rover rover)          : base(rover)      {      }      public override void Execute()      {          Rover.Rotate(-5.0);      }  }C#-OOF# type Command = Command of (Rover -> unit)let BreakCommand=   Command(fun rover -> rover.Accelerate(-1.0))let TurnLeftCommand =   Command(fun rover -> rover.Rotate(-5.0<degs>)) 
Simplicity: Functional DataC#let swap (x, y) = (y, x)let rotations (x, y, z) =     [ (x, y, z);      (z, x, y);      (y, z, x) ]let reduce f (x, y, z) =     f x + f y + f zTuple<U,T> Swap<T,U>(Tuple<T,U> t){    return new Tuple<U,T>(t.Item2, t.Item1)}ReadOnlyCollection<Tuple<T,T,T>> Rotations<T>(Tuple<T,T,T> t) {   new ReadOnlyCollection<int>   (new Tuple<T,T,T>[]     { new Tuple<T,T,T>(t.Item1,t.Item2,t.Item3);            new Tuple<T,T,T>(t.Item3,t.Item1,t.Item2);        new Tuple<T,T,T>(t.Item2,t.Item3,t.Item1); });}int Reduce<T>(Func<T,int> f,Tuple<T,T,T> t) {     return f(t.Item1) + f(t.Item2) + f (t.Item3); }F#
Simplicity: Functional DataC#public abstract class Expr { }   public abstract class UnaryOp :Expr   {       public Expr First { get; private set; }       public UnaryOp(Expr first)   { this.First = first; }   }   public abstract class BinExpr : Expr   {       public Expr First { get; private set; }       public Expr Second { get; private set; }       public BinExpr(Expr first, Expr second)   {           this.First = first;           this.Second = second;       }   }   public class TrueExpr : Expr { }     public class And : BinExpr   {       public And(Expr first, Expr second) : base(first, second) { } }public class Nand : BinExpr   {     public Nand(Expr first, Expr second) : base(first, second{ } }   public class Or : BinExpr   {       public Or(Expr first, Expr second) : base(first, second) { }  }   public class Xor : BinExpr   {       public Xor(Expr first, Expr second) : base(first, second) { }  }   public class Not : UnaryOp   {       public Not(Expr first) : base(first) { }   }  F#type Expr =       | True       | And of Expr * Expr       | Nand of Expr * Expr       | Or of Expr * Expr       | Xor of Expr * Expr       | Not of Expr  
Simplicity: Functional DataC#public abstract class Event { }   public abstract class PriceEvent : Event   {       public Price Price { get; private set; }       public PriceEvent(Price price)       {           this.Price = price;       }   }     public abstract class SplitExpr : Event   {       public double Factor { get; private set; }         public SplitExpr(double factor)       {           this.Factor = factor;       }   }     public class DividendEvent : Event { }     ...   type Event =    | Price of float    | Split of float    | Dividend of float<money>F#
Parallel
Async.Parallel [ http "www.google.com";                 http "www.bing.com";                 http "www.yahoo.com"; ]|> Async.RunSynchronously
Async.Parallel [ for i in 0 .. 200 -> computeTask i ]|> Async.RunSynchronously
F#:  InfluencesF#Similar core languageSimilar objectmodel
Let’s Web Crawl…Demo: Event Processing
Example #1 : MethodologyI've been coding in F# lately, for a production task. F# allows you to move smoothly in your programming style... I start with pure functional code, shift slightly towards an object-oriented style, and in production code, I sometimes have to do some imperative programming. I can start with a pure idea, and still finish my project with realistic code. You're never disappointed in any phase of the project!Julien Laugel, Chief Software Architect, www.eurostocks.com
Example #2 (power company)I have written an application to balance the national power generation schedule for a portfolio of power stations to a trading position for an energy company. ...the calculation engine was written in F#. The use of F# to address the complexity at the heart of this application clearly demonstrates a sweet spot for the language within enterprise software, namely algorithmically complex analysis of large data sets. Simon Cousins (power company)
Example #2 (power company) Units of measureThe industry I work in is littered with units....Having the type system verify the correctness of the units is a huge time saver...it eradicates a whole class of errors that previous systems were prone to.Exploratory programmingWorking with F# Interactive allowed me to explore the solution space more effectively before committing to an implementation ... a very natural way for a programmer to build their understanding of the problem and the design tensions in play.Unit testingCode written using non-side effecting functions and immutable data structures is a joy to test. There are no complex time-dependent interactions to screw things up or large sets of dependencies to be mocked.Parallelism The functional purity ... makes it ripe for exploiting the inherent parallelism in processing vectors of data. Interoperation ... The calculation engine could be injected into any C# module that needed to use it without any concerns at all about interoperability. Seamless. The C# programmer need never know.Code reductionMuch of the data fed into the calculation engine was in the form of vectors and matrices. Higher order functions eat these for breakfast with minimal fuss, minimal code. Beautiful.Lack of bugsFunctional programming can feel strange.  .. once the type checker is satisfied that’s it, it works.
Case Study #2 (power company)Units of measureThe industry I work in is littered with units....Having the type system verify the correctness of the units is a huge time saver...it eradicates a whole class of errors that previous systems were prone to.Exploratory programming Working with F# Interactive allowed me to explore the solution space more effectively before committing to an implementation ... a very natural way for a programmer to build their understanding of the problem and the design tensions in play.Unit testingCode written using non-side effecting functions and immutable data structures is a joy to test. There are no complex time-dependent interactions to screw things up or large sets of dependencies to be mocked.Parallelism The functional purity ... makes it ripe for exploiting the inherent parallelism in processing vectors of data. Interoperation... The calculation engine could be injected into any C# module that needed to use it without any concerns at all about interoperability. Seamless. The C# programmer need never know.Code reductionMuch of the data fed into the calculation engine was in the form of vectors and matrices. Higher order functions eat these for breakfast with minimal fuss, minimal code. Beautiful.Lack of bugs Functional programming can feel strange.  .. once the type checker is satisfied that’s it, it works.
Case Study #1: Grange Insurance
Case Study #2: “Finance Company”Source: http://whitepapers.techrepublic.com
The adCenter Problem
AdPredict: What We ObservedQuick CodingAgile CodingScriptingPerformanceMemory-FaithfulSuccinctSymbolic.NET IntegrationF#’s powerful type inference means less typing, more thinkingType-inferred code is easily refactored“Hands-on” exploration. Immediate scaling to massive data setsmega-data structures, 16GB machinesLive in the domain, not the languageSchema compilation and “Schedules”Especially Excel, SQL Server
Let’s Web Crawl…Topic: Some Basics
Fundamentals - Whitespace MattersletcomputeDerivative f x = letp1 = f (x - 0.05)  letp2 = f (x + 0.05)       (p2 – p1) / 0.1Offside (bad indentation)
Fundamentals - Whitespace MattersletcomputeDerivative f x = letp1 = f (x - 0.05)letp2 = f (x + 0.05)    (p2 – p1) / 0.1
Your First F# Applicationprintfn "Hello World"C:\test> fsctest.fsC:\test> test.exeHello WorldC:\test>
Your Second F# Applicationopen System.Windows.Formlet form = new Form (Visible=true)form.Click.Add (fun _ -> printfn "click")Application.Run form
Fundamentals: LetLet “let” simplify your life…Type inference.  The safety of C# with the succinctness of a scripting languageBind a static valuelet data = (1, 2, 3)let f (a, b, c) = let sum = a + b + c let g x = sum + x*x   (g a, g b, g c)Bind a static functionBind a local valueBind a local function
Functional– Pipelines           x |> fThe pipeline operator
Functional– Pipelines           x |> f1             |> f2             |> f3Successive stages in a pipeline
F# - Objects + Functionaltype Vector2D (dx:double, dy:double) =let d2 = dx*dx+dy*dymember v.DX = dxmemberv.DY = dymember v.Length = sqrt d2memberv.Scale(k) = Vector2D (dx*k,dy*k)Inputs to object constructionObject internalsExported propertiesExported method
Let’s Web Crawl…Demo: 3d Simulation
Resource: F# Object Oriented Quick GuideSource: F# Object-Oriented Quick Guide
ObjectsClass TypestypeObjectType(args) =letinternalValue = exprletinternalFunctionargs= exprletmutableinternalState = exprmemberx.Prop1 = exprmemberx.Meth2 args = exprInterface TypestypeIObject = interfaceISimpleObjectabstractProp1 : typeabstractMeth2 : type -> typeConstructing ObjectsnewFileInfo(@"c:\misc\test.fs")
Class with Properties
Class with Multiple Constructors
Class with Members + Private
+quick guide has more....Structs with propertiesMember functionsOperatorsStatic members and propertiesClass properties that use let value computations in the constructorOverloading membersMutable fields in a class with get/set propertiesGeneric classes and function argumentsExtension methodsExtension propertiesIndexersIndexed PropertiesAbstract classesDerive from a base class and overriding base methods with genericsCalling a base class methodImplementing an interfaceImplementing an interface with object expressionsEventsExplicit class constructor Explicit public fieldsExplicit struct definition
Topic: Units of Measure
Units of Measure – Typical Example[<Measure>] type money [<Measure>] type shares[<Measure>] type volume [<Measure>] typerateOfReturnletrateOfReturn (f:float) = f * 1.<rateOfReturn>type Price = { Open: float<money>;                High: float<money>;                Low: float<money>;                Close: float<money>;                Volume: float<volume> }
Let’s Web Crawl…Topic: async/parallel
React!async { let! res = <async-event>        ...  }React to a GUI EventReact to a Timer CallbackReact to a Query ResponseReact to a HTTP ResponseReact to a Web Service ResponseReact to a Disk I/O CompletionAgent reacts to Message
The many uses of async { ... }Sequencing I/O requestsSequencing CPU computations and I/O requestsasync { let! lang  = detectLanguageAsync textlet! text2 = translateAsync (lang,"da",text)return text2 }async { let! lang  = detectLanguageAsync textlet! text2 = translateAsync (lang,"da",text)let text3 = postProcess text2return text3 }
The many uses of async { ... }Parallel CPU computationsParallel I/O requestsAsync.Parallel [ async { return (fib 39) };                 async { return (fib 40) }; ]Async.Parallel   [ for target in langs -> translateAsync (lang,target,text) ]
F# example: Serving 5,000+ simultaneous TCP connections with ~10 threadsReact!React!React!
Agents/Actors
Your First Agentlet agent = Agent.Start(fun inbox ->         async { while true dolet! msg = inbox.Receive()                   printfn "got message %s" msg } )agent.Post "three"agent.Post "four"Note:type Agent<'T> = MailboxProcessor<'T>
Your First 100,000 Agentslet agents =    [ for i in 0 .. 100000 ->Agent.Start(fun inbox ->         async { while true dolet! msg = inbox.Receive()                   printfn "%d got message %s" i msg })]for agent in agents do agent.Post "hello"Note:type Agent<'T> = MailboxProcessor<'T>
Agents Galoredemo
Professional Tools
In Summary
We’ve been busy 
Plus…July 2010: Community TemplatesAugust 2010: Windows Phone TemplatesAugust 2010: Mono/Linux/Mac/.NET 4.0 + Visual Studio 2010 Shell Free Tools ReleaseNovember 5: F# in Education Workshop, Boston
Latest Books about F#Visit 	www.fsharp.net
Questions http://fsharp.nethttp://blogs.msdn.com/dsymehttp://meetup.com/FSharpLondon
© 2009 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation.  Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation.  MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
Shared StateF# and the Concurrency ChallengesF#  Immutability Inversion of ControlF# Async I/O ParallelismF# Async Messaging and ScalingF# Agents + Web/Azure/MSQ/HPC/Cluster etc.
Immutability the norm...Immutable ListsImmutable RecordsImmutable SetsImmutable ObjectsImmutable TuplesImmutable DictionariesImmutable Unions+ lots of language features to encourage immutability
In Praise of ImmutabilityImmutable objects can transfer between threadsImmutable objects never have race conditions
Parallel Async Stock TickersletloadTickerAsync ticker span =    async { let prices = loadPricesAsync ticker spanletdivs   = loadDivsAsync ticker spanlet splits = loadSplitsAsync ticker spanlet! (prices, divs, splits) =                 Async.Parallel3 (prices, divs, splits)return prices @ divs @ splits  }letloadTickersAsynctickerSpanTuples =  Async.Parallel      [ for (ticker, span) intickerSpanTuples ->          async { let!obs = loadTickerAsync ticker spanreturn (ticker, span, obs) } ]
NASA Mars Climate Orbiter, 1999
let EarthMass = 5.9736e24<kg>// Average between pole and equator radiilet EarthRadius = 6371.0e3<m>// Gravitational acceleration on surface of Earth let g = PhysicalConstants.G * EarthMass / (EarthRadius * EarthRadius)

London F-Sharp User Group : Don Syme on F# - 09/09/2010

  • 1.
    A Taste ofF# TodayDon Syme, Principal ResearcherMicrosoft Research, Cambridge
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
    F# is…...a programminglanguage that allows you to write simple codeto solve complex problems.
  • 8.
    F# is…...a productive,supported, functionalprogramming language that allows you to write simple codeto solve complex problems.
  • 9.
    Why is F#appealing in …
  • 10.
    Why is F#appealing in finance?
  • 11.
    Why is F#appealing in finance?A great fit for much financial work“Programmatic modelling” A typed, efficient scripting language goes a long wayPlays differently for different roles:Enables quants to contribute componentsEnables architects to explore hard problemsEnables developers to tackle parallel and async
  • 12.
    Crossing boundariesPerformance +Professional Development“Programming”“Financial engineering”C++C#JavaF#“QF modelling”Dynamic Domain SpecificProgrammingExpressivity for Mathematical tasks
  • 13.
    F# FundamentalsSuccinct, Expressive,Functional Language Parallel, Explorative, Data-rich, AlgorithmicIndustry/Platform-Leading Note: F# is not a replacement for C#/VB/C++ Augments and builds on .NET as multi-lang platform
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
    using System;namespace ConsoleApplication1{classProgram{static string greeting= "hello"static void Main(string[] args){Console.WriteLine(greeting); }}}open Systemlet greeting = "hello"Console.WriteLine(greeting)Simplicity: ScriptingC#F#
  • 19.
    Simplicity: Functions asValues   abstract class Command    {      public virtual void Execute();    }    abstract class RoverCommand: Command    {     protected Rover Rover { get; private set; }      public RoverCommand(MarsRoverrover)      {        this.Rover = rover;      }    }    class BreakCommand: RoverCommand    {      public BreakCommand(Rover rover)          : base(rover)      {      }       public override void Execute()      {          Rover.Rotate(-5.0);      }  } class TurnLeftCommand : RoverCommand  {      public TurnLeftCommand(Rover rover)          : base(rover)      {      }      public override void Execute()      {          Rover.Rotate(-5.0);      }  }C#-OOF# type Command = Command of (Rover -> unit)let BreakCommand= Command(fun rover -> rover.Accelerate(-1.0))let TurnLeftCommand = Command(fun rover -> rover.Rotate(-5.0<degs>)) 
  • 20.
    Simplicity: Functional DataC#letswap (x, y) = (y, x)let rotations (x, y, z) = [ (x, y, z); (z, x, y); (y, z, x) ]let reduce f (x, y, z) = f x + f y + f zTuple<U,T> Swap<T,U>(Tuple<T,U> t){ return new Tuple<U,T>(t.Item2, t.Item1)}ReadOnlyCollection<Tuple<T,T,T>> Rotations<T>(Tuple<T,T,T> t) { new ReadOnlyCollection<int> (new Tuple<T,T,T>[] { new Tuple<T,T,T>(t.Item1,t.Item2,t.Item3); new Tuple<T,T,T>(t.Item3,t.Item1,t.Item2); new Tuple<T,T,T>(t.Item2,t.Item3,t.Item1); });}int Reduce<T>(Func<T,int> f,Tuple<T,T,T> t) { return f(t.Item1) + f(t.Item2) + f (t.Item3); }F#
  • 21.
    Simplicity: Functional DataC#public abstract class Expr { }  public abstract class UnaryOp :Expr   {       public Expr First { get; private set; }       public UnaryOp(Expr first)   { this.First = first; }   }   public abstract class BinExpr : Expr   {       public Expr First { get; private set; }       public Expr Second { get; private set; }       public BinExpr(Expr first, Expr second)   {           this.First = first;           this.Second = second;       }   }   public class TrueExpr : Expr { }     public class And : BinExpr   {       public And(Expr first, Expr second) : base(first, second) { } }public class Nand : BinExpr   {     public Nand(Expr first, Expr second) : base(first, second{ } }   public class Or : BinExpr   {       public Or(Expr first, Expr second) : base(first, second) { }  }   public class Xor : BinExpr   {       public Xor(Expr first, Expr second) : base(first, second) { }  }   public class Not : UnaryOp   {       public Not(Expr first) : base(first) { }   }  F#type Expr =       | True       | And of Expr * Expr       | Nand of Expr * Expr       | Or of Expr * Expr       | Xor of Expr * Expr       | Not of Expr  
  • 22.
    Simplicity: Functional DataC#public abstract class Event { }  public abstract class PriceEvent : Event   {       public Price Price { get; private set; }       public PriceEvent(Price price)       {           this.Price = price;       }   }     public abstract class SplitExpr : Event   {       public double Factor { get; private set; }         public SplitExpr(double factor)       {           this.Factor = factor;       }   }     public class DividendEvent : Event { }     ...   type Event = | Price of float | Split of float | Dividend of float<money>F#
  • 23.
  • 24.
    Async.Parallel [ http"www.google.com"; http "www.bing.com"; http "www.yahoo.com"; ]|> Async.RunSynchronously
  • 25.
    Async.Parallel [ fori in 0 .. 200 -> computeTask i ]|> Async.RunSynchronously
  • 26.
    F#: InfluencesF#Similarcore languageSimilar objectmodel
  • 27.
  • 28.
    Example #1 :MethodologyI've been coding in F# lately, for a production task. F# allows you to move smoothly in your programming style... I start with pure functional code, shift slightly towards an object-oriented style, and in production code, I sometimes have to do some imperative programming. I can start with a pure idea, and still finish my project with realistic code. You're never disappointed in any phase of the project!Julien Laugel, Chief Software Architect, www.eurostocks.com
  • 29.
    Example #2 (powercompany)I have written an application to balance the national power generation schedule for a portfolio of power stations to a trading position for an energy company. ...the calculation engine was written in F#. The use of F# to address the complexity at the heart of this application clearly demonstrates a sweet spot for the language within enterprise software, namely algorithmically complex analysis of large data sets. Simon Cousins (power company)
  • 30.
    Example #2 (powercompany) Units of measureThe industry I work in is littered with units....Having the type system verify the correctness of the units is a huge time saver...it eradicates a whole class of errors that previous systems were prone to.Exploratory programmingWorking with F# Interactive allowed me to explore the solution space more effectively before committing to an implementation ... a very natural way for a programmer to build their understanding of the problem and the design tensions in play.Unit testingCode written using non-side effecting functions and immutable data structures is a joy to test. There are no complex time-dependent interactions to screw things up or large sets of dependencies to be mocked.Parallelism The functional purity ... makes it ripe for exploiting the inherent parallelism in processing vectors of data. Interoperation ... The calculation engine could be injected into any C# module that needed to use it without any concerns at all about interoperability. Seamless. The C# programmer need never know.Code reductionMuch of the data fed into the calculation engine was in the form of vectors and matrices. Higher order functions eat these for breakfast with minimal fuss, minimal code. Beautiful.Lack of bugsFunctional programming can feel strange. .. once the type checker is satisfied that’s it, it works.
  • 31.
    Case Study #2(power company)Units of measureThe industry I work in is littered with units....Having the type system verify the correctness of the units is a huge time saver...it eradicates a whole class of errors that previous systems were prone to.Exploratory programming Working with F# Interactive allowed me to explore the solution space more effectively before committing to an implementation ... a very natural way for a programmer to build their understanding of the problem and the design tensions in play.Unit testingCode written using non-side effecting functions and immutable data structures is a joy to test. There are no complex time-dependent interactions to screw things up or large sets of dependencies to be mocked.Parallelism The functional purity ... makes it ripe for exploiting the inherent parallelism in processing vectors of data. Interoperation... The calculation engine could be injected into any C# module that needed to use it without any concerns at all about interoperability. Seamless. The C# programmer need never know.Code reductionMuch of the data fed into the calculation engine was in the form of vectors and matrices. Higher order functions eat these for breakfast with minimal fuss, minimal code. Beautiful.Lack of bugs Functional programming can feel strange. .. once the type checker is satisfied that’s it, it works.
  • 32.
    Case Study #1:Grange Insurance
  • 33.
    Case Study #2:“Finance Company”Source: http://whitepapers.techrepublic.com
  • 34.
  • 35.
    AdPredict: What WeObservedQuick CodingAgile CodingScriptingPerformanceMemory-FaithfulSuccinctSymbolic.NET IntegrationF#’s powerful type inference means less typing, more thinkingType-inferred code is easily refactored“Hands-on” exploration. Immediate scaling to massive data setsmega-data structures, 16GB machinesLive in the domain, not the languageSchema compilation and “Schedules”Especially Excel, SQL Server
  • 37.
  • 38.
    Fundamentals - WhitespaceMattersletcomputeDerivative f x = letp1 = f (x - 0.05) letp2 = f (x + 0.05) (p2 – p1) / 0.1Offside (bad indentation)
  • 39.
    Fundamentals - WhitespaceMattersletcomputeDerivative f x = letp1 = f (x - 0.05)letp2 = f (x + 0.05) (p2 – p1) / 0.1
  • 40.
    Your First F#Applicationprintfn "Hello World"C:\test> fsctest.fsC:\test> test.exeHello WorldC:\test>
  • 41.
    Your Second F#Applicationopen System.Windows.Formlet form = new Form (Visible=true)form.Click.Add (fun _ -> printfn "click")Application.Run form
  • 42.
    Fundamentals: LetLet “let”simplify your life…Type inference. The safety of C# with the succinctness of a scripting languageBind a static valuelet data = (1, 2, 3)let f (a, b, c) = let sum = a + b + c let g x = sum + x*x (g a, g b, g c)Bind a static functionBind a local valueBind a local function
  • 43.
    Functional– Pipelines x |> fThe pipeline operator
  • 44.
    Functional– Pipelines x |> f1 |> f2 |> f3Successive stages in a pipeline
  • 45.
    F# - Objects+ Functionaltype Vector2D (dx:double, dy:double) =let d2 = dx*dx+dy*dymember v.DX = dxmemberv.DY = dymember v.Length = sqrt d2memberv.Scale(k) = Vector2D (dx*k,dy*k)Inputs to object constructionObject internalsExported propertiesExported method
  • 46.
  • 47.
    Resource: F# ObjectOriented Quick GuideSource: F# Object-Oriented Quick Guide
  • 48.
    ObjectsClass TypestypeObjectType(args) =letinternalValue= exprletinternalFunctionargs= exprletmutableinternalState = exprmemberx.Prop1 = exprmemberx.Meth2 args = exprInterface TypestypeIObject = interfaceISimpleObjectabstractProp1 : typeabstractMeth2 : type -> typeConstructing ObjectsnewFileInfo(@"c:\misc\test.fs")
  • 49.
  • 50.
  • 51.
  • 52.
    +quick guide hasmore....Structs with propertiesMember functionsOperatorsStatic members and propertiesClass properties that use let value computations in the constructorOverloading membersMutable fields in a class with get/set propertiesGeneric classes and function argumentsExtension methodsExtension propertiesIndexersIndexed PropertiesAbstract classesDerive from a base class and overriding base methods with genericsCalling a base class methodImplementing an interfaceImplementing an interface with object expressionsEventsExplicit class constructor Explicit public fieldsExplicit struct definition
  • 53.
  • 54.
    Units of Measure– Typical Example[<Measure>] type money [<Measure>] type shares[<Measure>] type volume [<Measure>] typerateOfReturnletrateOfReturn (f:float) = f * 1.<rateOfReturn>type Price = { Open: float<money>; High: float<money>; Low: float<money>; Close: float<money>; Volume: float<volume> }
  • 55.
  • 56.
    React!async { let!res = <async-event> ... }React to a GUI EventReact to a Timer CallbackReact to a Query ResponseReact to a HTTP ResponseReact to a Web Service ResponseReact to a Disk I/O CompletionAgent reacts to Message
  • 59.
    The many usesof async { ... }Sequencing I/O requestsSequencing CPU computations and I/O requestsasync { let! lang = detectLanguageAsync textlet! text2 = translateAsync (lang,"da",text)return text2 }async { let! lang = detectLanguageAsync textlet! text2 = translateAsync (lang,"da",text)let text3 = postProcess text2return text3 }
  • 60.
    The many usesof async { ... }Parallel CPU computationsParallel I/O requestsAsync.Parallel [ async { return (fib 39) }; async { return (fib 40) }; ]Async.Parallel [ for target in langs -> translateAsync (lang,target,text) ]
  • 63.
    F# example: Serving5,000+ simultaneous TCP connections with ~10 threadsReact!React!React!
  • 65.
  • 66.
    Your First Agentletagent = Agent.Start(fun inbox -> async { while true dolet! msg = inbox.Receive() printfn "got message %s" msg } )agent.Post "three"agent.Post "four"Note:type Agent<'T> = MailboxProcessor<'T>
  • 67.
    Your First 100,000Agentslet agents = [ for i in 0 .. 100000 ->Agent.Start(fun inbox -> async { while true dolet! msg = inbox.Receive() printfn "%d got message %s" i msg })]for agent in agents do agent.Post "hello"Note:type Agent<'T> = MailboxProcessor<'T>
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
    Plus…July 2010: CommunityTemplatesAugust 2010: Windows Phone TemplatesAugust 2010: Mono/Linux/Mac/.NET 4.0 + Visual Studio 2010 Shell Free Tools ReleaseNovember 5: F# in Education Workshop, Boston
  • 73.
    Latest Books aboutF#Visit www.fsharp.net
  • 74.
  • 75.
    © 2009 MicrosoftCorporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
  • 76.
    Shared StateF# andthe Concurrency ChallengesF# Immutability Inversion of ControlF# Async I/O ParallelismF# Async Messaging and ScalingF# Agents + Web/Azure/MSQ/HPC/Cluster etc.
  • 77.
    Immutability the norm...ImmutableListsImmutable RecordsImmutable SetsImmutable ObjectsImmutable TuplesImmutable DictionariesImmutable Unions+ lots of language features to encourage immutability
  • 78.
    In Praise ofImmutabilityImmutable objects can transfer between threadsImmutable objects never have race conditions
  • 79.
    Parallel Async StockTickersletloadTickerAsync ticker span = async { let prices = loadPricesAsync ticker spanletdivs = loadDivsAsync ticker spanlet splits = loadSplitsAsync ticker spanlet! (prices, divs, splits) = Async.Parallel3 (prices, divs, splits)return prices @ divs @ splits }letloadTickersAsynctickerSpanTuples = Async.Parallel [ for (ticker, span) intickerSpanTuples -> async { let!obs = loadTickerAsync ticker spanreturn (ticker, span, obs) } ]
  • 80.
    NASA Mars ClimateOrbiter, 1999
  • 81.
    let EarthMass =5.9736e24<kg>// Average between pole and equator radiilet EarthRadius = 6371.0e3<m>// Gravitational acceleration on surface of Earth let g = PhysicalConstants.G * EarthMass / (EarthRadius * EarthRadius)

Editor's Notes

  • #20 If you would like to host your demo on the Virtual Server, please use the myVPC demo slide, not this slide.
  • #36 If you would like to host your demo on the Virtual Server, please use the myVPC demo slide, not this slide.
  • #38 If you would like to host your demo on the Virtual Server, please use the myVPC demo slide, not this slide.
  • #55 If you would like to host your demo on the Virtual Server, please use the myVPC demo slide, not this slide.