SlideShare uma empresa Scribd logo
1 de 81
A Taste of F# Today Don Syme,  Principal Researcher Microsoft 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 way Plays differently for different roles: Enables quants to contribute components Enables architects to explore hard problems Enables developers to tackle parallel and async
Crossing boundaries Performance + Professional  Development “Programming” “Financial engineering” C++ C# Java F# “QF modelling” Dynamic  Domain Specific Programming Expressivity for  Mathematical tasks
F# Fundamentals Succinct, Expressive, Functional Language  Parallel, Explorative, Data-rich, Algorithmic Industry/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 System let greeting = "hello" Console.WriteLine(greeting) Simplicity: Scripting C# 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#-OO F#   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 Data C# 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 z Tuple<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 Data C# 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 Data C# 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#:  Influences F# Similar core  language Similar object model
Let’s Web Crawl… Demo: Event Processing
Example #1 : Methodology I'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 Observed Quick Coding Agile Coding Scripting Performance Memory-Faithful Succinct Symbolic .NET Integration F#’s powerful type inference means less typing, more thinking Type-inferred code is easily refactored “Hands-on” exploration.  Immediate scaling to massive data sets mega-data structures, 16GB machines Live in the domain, not the language Schema compilation and “Schedules” Especially Excel, SQL Server
Let’s Web Crawl… Topic: Some Basics
Fundamentals - Whitespace Matters letcomputeDerivative f x =  letp1 = f (x - 0.05)   letp2 = f (x + 0.05)        (p2 – p1) / 0.1 Offside (bad indentation)
Fundamentals - Whitespace Matters letcomputeDerivative f x =  letp1 = f (x - 0.05) letp2 = f (x + 0.05)     (p2 – p1) / 0.1
Your First F# Application printfn "Hello World" C:est> fsctest.fs C:est> test.exe Hello World C:est>
Your Second F# Application open System.Windows.Form let form = new Form (Visible=true) form.Click.Add (fun _ -> printfn "click") Application.Run form
Fundamentals: Let Let “let” simplify your life… Type inference.  The safety of C# with the succinctness of a scripting language Bind a static value let 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 function Bind a local value Bind a local function
Functional– Pipelines            x |> f The pipeline operator
Functional– Pipelines            x |> f1              |> f2              |> f3 Successive stages  in a pipeline
F# - Objects + Functional type Vector2D (dx:double, dy:double) = let d2 = dx*dx+dy*dy member v.DX = dx memberv.DY = dy member v.Length = sqrt d2 memberv.Scale(k) = Vector2D (dx*k,dy*k) Inputs to object  construction Object internals Exported properties Exported method
Let’s Web Crawl… Demo: 3d Simulation
Resource: F# Object Oriented Quick Guide Source: F# Object-Oriented Quick Guide
Objects Class Types typeObjectType(args) = letinternalValue = expr letinternalFunctionargs= expr letmutableinternalState = expr memberx.Prop1 = expr memberx.Meth2 args = expr Interface Types typeIObject =  interfaceISimpleObject abstractProp1 : type abstractMeth2 : type -> type Constructing Objects newFileInfo(@"c:iscest.fs")
Class with Properties
Class with Multiple Constructors
Class with Members + Private
+quick guide has more.... Structs with properties Member functions Operators Static members and properties Class properties that use let value computations in the constructor Overloading members Mutable fields in a class with get/set properties Generic classes and function arguments Extension methods Extension properties Indexers Indexed Properties Abstract classes Derive from a base class and overriding base methods with generics Calling a base class method Implementing an interface Implementing an interface with object expressions Events Explicit class constructor  Explicit public fields Explicit struct definition
Topic: Units of Measure
Units of Measure – Typical Example [<Measure>] type money  [<Measure>] type shares [<Measure>] type volume  [<Measure>] typerateOfReturn letrateOfReturn (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 Event React to a Timer Callback React to a Query Response React to a HTTP Response React to a Web Service Response React to a Disk I/O Completion Agent reacts to Message
The many uses of async { ... } Sequencing I/O requests Sequencing CPU computations and I/O requests async { let! lang  = detectLanguageAsync text let! text2 = translateAsync (lang,"da",text) return text2 } async { let! lang  = detectLanguageAsync text let! text2 = translateAsync (lang,"da",text) let text3 = postProcess text2 return text3 }
The many uses of async { ... } Parallel CPU computations Parallel I/O requests Async.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 threads React! React! React!
Agents/Actors
Your First Agent let agent =  Agent.Start(fun inbox ->          async { while true do let! msg = inbox.Receive()                    printfn "got message %s" msg } ) agent.Post "three" agent.Post "four" Note: type Agent<'T> = MailboxProcessor<'T>
Your First 100,000 Agents let agents =     [ for i in 0 .. 100000 -> Agent.Start(fun inbox ->          async { while true do let! 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 Galore demo
Professional Tools
In Summary
We’ve been busy 
Plus… July 2010: Community Templates August 2010: Windows Phone Templates August 2010: Mono/Linux/Mac/.NET 4.0 + Visual Studio 2010 Shell Free Tools Release November 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 State F# and the Concurrency Challenges F#  Immutability  Inversion of Control F# Async  I/O Parallelism F# Async  Messaging and Scaling F# Agents  + Web/Azure/MSQ/ HPC/Cluster etc.
Immutability the norm... Immutable Lists Immutable Records Immutable Sets Immutable Objects Immutable Tuples Immutable Dictionaries Immutable Unions + lots of language features to encourage immutability
In Praise of Immutability Immutable objects can transfer between threads Immutable objects never have race conditions
Parallel Async Stock Tickers letloadTickerAsync ticker span =     async { let prices = loadPricesAsync ticker span letdivs   = loadDivsAsync ticker span let splits = loadSplitsAsync ticker span let! (prices, divs, splits) =                  Async.Parallel3 (prices, divs, splits) return prices @ divs @ splits  } letloadTickersAsynctickerSpanTuples =   Async.Parallel       [ for (ticker, span) intickerSpanTuples ->           async { let!obs = loadTickerAsync ticker span return (ticker, span, obs) } ]
NASA Mars Climate Orbiter, 1999
let EarthMass = 5.9736e24<kg> // Average between pole and equator radii let EarthRadius = 6371.0e3<m> // Gravitational acceleration on surface of Earth  let g = PhysicalConstants.G * EarthMass / (EarthRadius * EarthRadius)

Mais conteúdo relacionado

Destaque

F Melodic Minor Scale
F Melodic Minor ScaleF Melodic Minor Scale
F Melodic Minor Scaleqmlamb
 
Chords and Intervals
Chords and IntervalsChords and Intervals
Chords and Intervalsbrandongentis
 
Major and minor details
Major and minor detailsMajor and minor details
Major and minor detailsNichole Keith
 
K TO 12 GRADE 7 LEARNING MODULE IN MUSIC (Q3-Q4)
K TO 12 GRADE 7 LEARNING MODULE IN MUSIC (Q3-Q4)K TO 12 GRADE 7 LEARNING MODULE IN MUSIC (Q3-Q4)
K TO 12 GRADE 7 LEARNING MODULE IN MUSIC (Q3-Q4)LiGhT ArOhL
 

Destaque (7)

F Melodic Minor Scale
F Melodic Minor ScaleF Melodic Minor Scale
F Melodic Minor Scale
 
Music of palawan
Music of palawanMusic of palawan
Music of palawan
 
Chords and Intervals
Chords and IntervalsChords and Intervals
Chords and Intervals
 
Music theory
Music theoryMusic theory
Music theory
 
Major and minor details
Major and minor detailsMajor and minor details
Major and minor details
 
Rudiments of music
Rudiments of musicRudiments of music
Rudiments of music
 
K TO 12 GRADE 7 LEARNING MODULE IN MUSIC (Q3-Q4)
K TO 12 GRADE 7 LEARNING MODULE IN MUSIC (Q3-Q4)K TO 12 GRADE 7 LEARNING MODULE IN MUSIC (Q3-Q4)
K TO 12 GRADE 7 LEARNING MODULE IN MUSIC (Q3-Q4)
 

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

Succeeding with Functional-first Programming in Enterprise
Succeeding with Functional-first Programming in EnterpriseSucceeding with Functional-first Programming in Enterprise
Succeeding with Functional-first Programming in Enterprisedsyme
 
What every C++ programmer should know about modern compilers (w/ comments, AC...
What every C++ programmer should know about modern compilers (w/ comments, AC...What every C++ programmer should know about modern compilers (w/ comments, AC...
What every C++ programmer should know about modern compilers (w/ comments, AC...Sławomir Zborowski
 
MEL_WOLINSKY_20170124
MEL_WOLINSKY_20170124MEL_WOLINSKY_20170124
MEL_WOLINSKY_20170124Mel Wolinsky
 
Week 4 Assignment - Software Development PlanScenario-Your team has be.docx
Week 4 Assignment - Software Development PlanScenario-Your team has be.docxWeek 4 Assignment - Software Development PlanScenario-Your team has be.docx
Week 4 Assignment - Software Development PlanScenario-Your team has be.docxestefana2345678
 
Code instrumentation
Code instrumentationCode instrumentation
Code instrumentationMennan Tekbir
 
Going open source with small teams
Going open source with small teamsGoing open source with small teams
Going open source with small teamsJamie Thomas
 
Overview Of Parallel Development - Ericnel
Overview Of Parallel Development -  EricnelOverview Of Parallel Development -  Ericnel
Overview Of Parallel Development - Ericnelukdpe
 
Production Debugging at Code Camp Philly
Production Debugging at Code Camp PhillyProduction Debugging at Code Camp Philly
Production Debugging at Code Camp PhillyBrian Lyttle
 
Demystifying dot NET reverse engineering - Part1
Demystifying  dot NET reverse engineering - Part1Demystifying  dot NET reverse engineering - Part1
Demystifying dot NET reverse engineering - Part1Soufiane Tahiri
 
Leverage the power of machine learning on windows
Leverage the power of machine learning on windowsLeverage the power of machine learning on windows
Leverage the power of machine learning on windowsMia Chang
 
Notes of c programming 1st unit BCA I SEM
Notes of c programming  1st unit BCA I SEMNotes of c programming  1st unit BCA I SEM
Notes of c programming 1st unit BCA I SEMMansi Tyagi
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review ProcessDr. Syed Hassan Amin
 
Flyte kubecon 2019 SanDiego
Flyte kubecon 2019 SanDiegoFlyte kubecon 2019 SanDiego
Flyte kubecon 2019 SanDiegoKetanUmare
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentEffective
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentEffectiveUI
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentJohn Blanco
 

Semelhante a London F-Sharp User Group : Don Syme on F# - 09/09/2010 (20)

Succeeding with Functional-first Programming in Enterprise
Succeeding with Functional-first Programming in EnterpriseSucceeding with Functional-first Programming in Enterprise
Succeeding with Functional-first Programming in Enterprise
 
What every C++ programmer should know about modern compilers (w/ comments, AC...
What every C++ programmer should know about modern compilers (w/ comments, AC...What every C++ programmer should know about modern compilers (w/ comments, AC...
What every C++ programmer should know about modern compilers (w/ comments, AC...
 
MEL_WOLINSKY_20170124
MEL_WOLINSKY_20170124MEL_WOLINSKY_20170124
MEL_WOLINSKY_20170124
 
Tdd is not about testing
Tdd is not about testingTdd is not about testing
Tdd is not about testing
 
Week 4 Assignment - Software Development PlanScenario-Your team has be.docx
Week 4 Assignment - Software Development PlanScenario-Your team has be.docxWeek 4 Assignment - Software Development PlanScenario-Your team has be.docx
Week 4 Assignment - Software Development PlanScenario-Your team has be.docx
 
Code instrumentation
Code instrumentationCode instrumentation
Code instrumentation
 
Going open source with small teams
Going open source with small teamsGoing open source with small teams
Going open source with small teams
 
F sharp - an overview
F sharp - an overviewF sharp - an overview
F sharp - an overview
 
Overview Of Parallel Development - Ericnel
Overview Of Parallel Development -  EricnelOverview Of Parallel Development -  Ericnel
Overview Of Parallel Development - Ericnel
 
Production Debugging at Code Camp Philly
Production Debugging at Code Camp PhillyProduction Debugging at Code Camp Philly
Production Debugging at Code Camp Philly
 
Intro1
Intro1Intro1
Intro1
 
Demystifying dot NET reverse engineering - Part1
Demystifying  dot NET reverse engineering - Part1Demystifying  dot NET reverse engineering - Part1
Demystifying dot NET reverse engineering - Part1
 
Leverage the power of machine learning on windows
Leverage the power of machine learning on windowsLeverage the power of machine learning on windows
Leverage the power of machine learning on windows
 
Notes of c programming 1st unit BCA I SEM
Notes of c programming  1st unit BCA I SEMNotes of c programming  1st unit BCA I SEM
Notes of c programming 1st unit BCA I SEM
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
 
Build 2019 Recap
Build 2019 RecapBuild 2019 Recap
Build 2019 Recap
 
Flyte kubecon 2019 SanDiego
Flyte kubecon 2019 SanDiegoFlyte kubecon 2019 SanDiego
Flyte kubecon 2019 SanDiego
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 

Mais de Skills Matter

5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard LawrenceSkills Matter
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applicationsSkills Matter
 
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmScala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmSkills Matter
 
Oscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimOscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimSkills Matter
 
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Skills Matter
 
Cukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlCukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlSkills Matter
 
Cukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsCukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsSkills Matter
 
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...Skills Matter
 
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...Skills Matter
 
Progressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source worldProgressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source worldSkills Matter
 
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...Skills Matter
 
Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#Skills Matter
 
A poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingA poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingSkills Matter
 
Russ miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveRuss miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveSkills Matter
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSkills Matter
 
I went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tI went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tSkills Matter
 

Mais de Skills Matter (20)

5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmScala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
 
Oscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimOscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheim
 
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
 
Cukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlCukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberl
 
Cukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsCukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.js
 
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
 
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
 
Progressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source worldProgressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source world
 
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
 
Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#
 
A poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingA poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testing
 
Russ miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveRuss miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-dive
 
Serendipity-neo4j
Serendipity-neo4jSerendipity-neo4j
Serendipity-neo4j
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelism
 
Plug 20110217
Plug   20110217Plug   20110217
Plug 20110217
 
Lug presentation
Lug presentationLug presentation
Lug presentation
 
I went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tI went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_t
 
Plug saiku
Plug   saikuPlug   saiku
Plug saiku
 

Último

Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 

Último (20)

Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 

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

  • 1. A Taste of F# Today Don Syme, Principal Researcher Microsoft Research, Cambridge
  • 6. F# is… a programminglanguage…
  • 7. F# is… ...a programming language 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 way Plays differently for different roles: Enables quants to contribute components Enables architects to explore hard problems Enables developers to tackle parallel and async
  • 12. Crossing boundaries Performance + Professional Development “Programming” “Financial engineering” C++ C# Java F# “QF modelling” Dynamic Domain Specific Programming Expressivity for Mathematical tasks
  • 13. F# Fundamentals Succinct, Expressive, Functional Language Parallel, Explorative, Data-rich, Algorithmic Industry/Platform-Leading Note: F# is not a replacement for C#/VB/C++ Augments and builds on .NET as multi-lang platform
  • 18. using System; namespace ConsoleApplication1 { class Program { static string greeting= "hello" static void Main(string[] args) { Console.WriteLine(greeting); } } } open System let greeting = "hello" Console.WriteLine(greeting) Simplicity: Scripting C# F#
  • 19. 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#-OO F#   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 Data C# 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 z Tuple<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 Data C# 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 Data C# 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#
  • 24. Async.Parallel [ http "www.google.com"; http "www.bing.com"; http "www.yahoo.com"; ] |> Async.RunSynchronously
  • 25. Async.Parallel [ for i in 0 .. 200 -> computeTask i ] |> Async.RunSynchronously
  • 26. F#: Influences F# Similar core language Similar object model
  • 27. Let’s Web Crawl… Demo: Event Processing
  • 28. Example #1 : Methodology I'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 (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)
  • 30. 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.
  • 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
  • 35. AdPredict: What We Observed Quick Coding Agile Coding Scripting Performance Memory-Faithful Succinct Symbolic .NET Integration F#’s powerful type inference means less typing, more thinking Type-inferred code is easily refactored “Hands-on” exploration. Immediate scaling to massive data sets mega-data structures, 16GB machines Live in the domain, not the language Schema compilation and “Schedules” Especially Excel, SQL Server
  • 36.
  • 37. Let’s Web Crawl… Topic: Some Basics
  • 38. Fundamentals - Whitespace Matters letcomputeDerivative f x = letp1 = f (x - 0.05) letp2 = f (x + 0.05) (p2 – p1) / 0.1 Offside (bad indentation)
  • 39. Fundamentals - Whitespace Matters letcomputeDerivative f x = letp1 = f (x - 0.05) letp2 = f (x + 0.05) (p2 – p1) / 0.1
  • 40. Your First F# Application printfn "Hello World" C:est> fsctest.fs C:est> test.exe Hello World C:est>
  • 41. Your Second F# Application open System.Windows.Form let form = new Form (Visible=true) form.Click.Add (fun _ -> printfn "click") Application.Run form
  • 42. Fundamentals: Let Let “let” simplify your life… Type inference. The safety of C# with the succinctness of a scripting language Bind a static value let 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 function Bind a local value Bind a local function
  • 43. Functional– Pipelines x |> f The pipeline operator
  • 44. Functional– Pipelines x |> f1 |> f2 |> f3 Successive stages in a pipeline
  • 45. F# - Objects + Functional type Vector2D (dx:double, dy:double) = let d2 = dx*dx+dy*dy member v.DX = dx memberv.DY = dy member v.Length = sqrt d2 memberv.Scale(k) = Vector2D (dx*k,dy*k) Inputs to object construction Object internals Exported properties Exported method
  • 46. Let’s Web Crawl… Demo: 3d Simulation
  • 47. Resource: F# Object Oriented Quick Guide Source: F# Object-Oriented Quick Guide
  • 48. Objects Class Types typeObjectType(args) = letinternalValue = expr letinternalFunctionargs= expr letmutableinternalState = expr memberx.Prop1 = expr memberx.Meth2 args = expr Interface Types typeIObject = interfaceISimpleObject abstractProp1 : type abstractMeth2 : type -> type Constructing Objects newFileInfo(@"c:iscest.fs")
  • 50. Class with Multiple Constructors
  • 51. Class with Members + Private
  • 52. +quick guide has more.... Structs with properties Member functions Operators Static members and properties Class properties that use let value computations in the constructor Overloading members Mutable fields in a class with get/set properties Generic classes and function arguments Extension methods Extension properties Indexers Indexed Properties Abstract classes Derive from a base class and overriding base methods with generics Calling a base class method Implementing an interface Implementing an interface with object expressions Events Explicit class constructor Explicit public fields Explicit struct definition
  • 53. Topic: Units of Measure
  • 54. Units of Measure – Typical Example [<Measure>] type money [<Measure>] type shares [<Measure>] type volume [<Measure>] typerateOfReturn letrateOfReturn (f:float) = f * 1.<rateOfReturn> type Price = { Open: float<money>; High: float<money>; Low: float<money>; Close: float<money>; Volume: float<volume> }
  • 55. Let’s Web Crawl… Topic: async/parallel
  • 56. React! async { let! res = <async-event> ... } React to a GUI Event React to a Timer Callback React to a Query Response React to a HTTP Response React to a Web Service Response React to a Disk I/O Completion Agent reacts to Message
  • 57.
  • 58.
  • 59. The many uses of async { ... } Sequencing I/O requests Sequencing CPU computations and I/O requests async { let! lang = detectLanguageAsync text let! text2 = translateAsync (lang,"da",text) return text2 } async { let! lang = detectLanguageAsync text let! text2 = translateAsync (lang,"da",text) let text3 = postProcess text2 return text3 }
  • 60. The many uses of async { ... } Parallel CPU computations Parallel I/O requests Async.Parallel [ async { return (fib 39) }; async { return (fib 40) }; ] Async.Parallel [ for target in langs -> translateAsync (lang,target,text) ]
  • 61.
  • 62.
  • 63. F# example: Serving 5,000+ simultaneous TCP connections with ~10 threads React! React! React!
  • 64.
  • 66. Your First Agent let agent = Agent.Start(fun inbox -> async { while true do let! msg = inbox.Receive() printfn "got message %s" msg } ) agent.Post "three" agent.Post "four" Note: type Agent<'T> = MailboxProcessor<'T>
  • 67. Your First 100,000 Agents let agents = [ for i in 0 .. 100000 -> Agent.Start(fun inbox -> async { while true do let! msg = inbox.Receive() printfn "%d got message %s" i msg })] for agent in agents do agent.Post "hello" Note: type Agent<'T> = MailboxProcessor<'T>
  • 72. Plus… July 2010: Community Templates August 2010: Windows Phone Templates August 2010: Mono/Linux/Mac/.NET 4.0 + Visual Studio 2010 Shell Free Tools Release November 5: F# in Education Workshop, Boston
  • 73. Latest Books about F# Visit www.fsharp.net
  • 75. © 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.
  • 76. Shared State F# and the Concurrency Challenges F# Immutability Inversion of Control F# Async I/O Parallelism F# Async Messaging and Scaling F# Agents + Web/Azure/MSQ/ HPC/Cluster etc.
  • 77. Immutability the norm... Immutable Lists Immutable Records Immutable Sets Immutable Objects Immutable Tuples Immutable Dictionaries Immutable Unions + lots of language features to encourage immutability
  • 78. In Praise of Immutability Immutable objects can transfer between threads Immutable objects never have race conditions
  • 79. Parallel Async Stock Tickers letloadTickerAsync ticker span = async { let prices = loadPricesAsync ticker span letdivs = loadDivsAsync ticker span let splits = loadSplitsAsync ticker span let! (prices, divs, splits) = Async.Parallel3 (prices, divs, splits) return prices @ divs @ splits } letloadTickersAsynctickerSpanTuples = Async.Parallel [ for (ticker, span) intickerSpanTuples -> async { let!obs = loadTickerAsync ticker span return (ticker, span, obs) } ]
  • 80. NASA Mars Climate Orbiter, 1999
  • 81. let EarthMass = 5.9736e24<kg> // Average between pole and equator radii let EarthRadius = 6371.0e3<m> // Gravitational acceleration on surface of Earth let g = PhysicalConstants.G * EarthMass / (EarthRadius * EarthRadius)

Notas do Editor

  1. If you would like to host your demo on the Virtual Server, please use the myVPC demo slide, not this slide.
  2. If you would like to host your demo on the Virtual Server, please use the myVPC demo slide, not this slide.
  3. If you would like to host your demo on the Virtual Server, please use the myVPC demo slide, not this slide.
  4. If you would like to host your demo on the Virtual Server, please use the myVPC demo slide, not this slide.