SlideShare a Scribd company logo
1 of 52
Turning to the Functional side
                (Using C# and F#)




    Phil Trelford           Tomas Petricek
http://trelford.com/blog   http://tomasp.net/blog
       @ptrelford              @tomaspetricek
About Us

» Tomas
   • Author of F# book for C# programmers
   • Worked with the F# team at Microsoft
   • First blogged about F# in May 2006


» Phil
   • Software Developer and Architect
   • Worked on first F# applications at Microsoft
   • Co-organizer of London F# User Group


» http://functional-programming.net
Tutorial

Goals
» Introduce Functional Concepts with F# and C#


Non-goals
» Provide in-depth understanding
» Mass conversion to functional programming cult
» Sell books
Thoughtworks Technology Radar July 2011
Visual F#
The F in F# stands for
FUN
Halo 3 with F# Skills
XBLA: Path to Go – F# AI
F#


» Strongly Typed
» Functional
» Object Orientated
» Open Source
» .Net language
» In Visual Studio
Functional Programing


» Pure Functions
» Higher Order Functions
» Pattern Matching
Pure Functions - Excel
Higher Order Functions
 F# Map/Reduce                     C# Map/Reduce
let map f xs = seq {               public static
                                       IEnumerable<R> Map<T, R>
   for x in xs do                      (this IEnumerable<T> xs,
                                           Func<T, R> f)
       yield f x                   {
                                       foreach (var x in xs)
   }                                       yield return f(x);
                                   }

let reduce f init items =          public static R
                                       Reduce<T, R>
   let mutable current = init          (this IEnumerable<T> xs,
                                        R init,
   for item in items do                Func<R, T, R> f)
                                   {
       current <- f current item       var current = init;
                                       foreach (var x in xs)
   current                                 current = f(current, x);
                                       return current;
                                   }
Pattern Matching
F#                          C#
match day with              switch (day) {
| 0 -> "Sunday"               case 0: return "Sunday";
                              case 1: return "Monday";
| 1 -> "Monday"               case 2: return "Tuesday";
| 2 -> "Tuesday"              case 3: return "Wednesday";
                              case 4: return "Thursday";
| 3 -> "Wednesday"            case 5: return "Friday";
| 4 -> "Thursday"             case 6: return "Saturday";
                              default:
| 5 -> "Friday"                 throw new
                                  ArgumentException("day");
| 6 -> "Saturday"
                            }
| _ –>

 invalidArg "Invalid day"
Light Syntax

F#                                   C#
                                     public class Person
type Person(name:string,age:int) =   {
                                         public Person(string name, int age)
   /// Full name                         {
                                             _name = name;
   member person.Name = name                 _age = age;
                                         }
   /// Age in years
                                         private readonly string _name;
   member person.Age = age               private readonly int _age;

                                         /// <summary>
                                         /// Full name
                                         /// </summary>
                                         public string Name
                                         {
                                             get { return _name; }
                                         }

                                         /// <summary>
                                         /// Age in years
                                         /// </summary>
                                         public int Age
                                         {
                                             get { return _age; }
                                         }
                                     }
Functional data structures

» A way of thinking about problems
» Model data using composition of primitives



       Tuple         Combine two values of different types

   Discriminated     Represents one of several options
       Union

        List         Zero or more values of the same type
Tuples: Containers for a few different things
Discriminated Unions: Exclusive alternatives
Representing event schedule

Object-oriented way                         Functional way
                Schedule                                    Schedule
                                                       Tag : ScheduleType
      GetNextOccurrence() : DateTime



     Once         Never        Repeatedly       Once         Never          Repeatedly




» Easy to add new cases                     » Easy to add new functions
» Hard to add new functions                 » Hard to add new cases


» Good thing about F# and Scala – you can use both!
Cutting the caterpillar

 Head                     Head



                                 Head
          Head


                                   Head




            End!
Functional Lists in C#

» List is either empty or nonempty

                                 List



                  Nonempty              Empty
                  (head, tail)



   • In C#, a class hierarchy with two classes
   • In F#, a discriminated union with two cases
Functional lists in C#


 public class FunctionalList<T> {
   // Creates a new list that is empty
   public FunctionalList();
   // Creates a non-empty list
   public FunctionalList(T head, FunctionalList<T> tail);

     // Is the list empty?
     public bool IsEmpty { get; }

     // Properties valid for a non-empty list
     public T Head { get; }
     public FunctionalList<T> Tail { get; }
 }
Domain Modelling

» Retail Domain -> Testing


» http://tomasp.net/fpday.zip
Processing Stock Prices
Yahoo Stock Prices

» Data stored in a CSV file
   Date,Open,High,Low,Close,Volume,Adj Close
   2011-10-12,407.34,409.25,400.14,402.19,22206600,402.19
   2011-10-11,392.57,403.18,391.50,400.29,21609800,400.29
   2011-10-10,379.09,388.81,378.21,388.81,15769200,388.81


» Read and print all data
   open System.IO

   let dir = __SOURCE_DIRECTORY__ + "dataaapl.csv"
   let lines = File.ReadAllLines(dir)
   for line in lines do
       printfn "%s" line
Parsing CSV data

» Get some data for testing
   let line1 = lines |> Seq.head
   let line2 = lines |> Seq.skip 1 |> Seq.head


» Using arrays in F#
   let arr = str.Split([| ',' |])
   arr.[0]


» Converting strings to numbers
   float "12.34"
   DateTime.Parse("1985-05-02")
TASK #1
Iterate over lines, parse CSV and print date & price
Sequence expressions

» Exploring data using imperative loops
    for year, value in yearlyAverages do
      if value < 25.0 then
        printfn "%d (only %f)" year value

» Can be turned into a sequence expression…
    let badYears =
      seq { for year, value in yearlyAverages do
              if value < 25.0 then
                yield year, value }

   • Result has a type seq<int * float> (IEnumerable)
   • Brackets: [| … |] for arrays, [ … ] for lists, set [ … ] for sets
TASK #2
Turn the parsing into a sequence expression
Organizing Source Code

» Compiled Libraries
   • Allow C# users call F# code
   • Encapsulate (complete) functionality
» F# Script Files
   • Great for explorative programming
   • Script can load some other files

  // File1.fsx                   // File2.fsx
  module StockData               #load "File1.fsx"
                                 open StockData
  let getData name =
    name, 99.0                   getData "MSFT"
TASK #3
Write function that parses specified CSV file
Processing Data in F#

» Writing data processing query in F#

       Lambda function                   All types are inferred
  StockData.MSFT
  |> Seq.filter (fun stock -> stock.Close - stock.Open > 7.0)
  |> Seq.map (fun stock -> stock.Date)
  |> Seq.iter (printfn "%A")
                                    Partial function application
          Custom operators

» Seq module provides functions for IEnumerable
   • But some operations make only sense for arrays/lists
» Sequence expressions provide query-like syntax
Useful functions

» Basic Functions
   • Seq.filter – filter elements using predicate (aka Where)
   • Seq.map – turn values into different (aka Select)
» Aggregating all elements of a sequence
   • Seq.max, Seq.min, Seq.averag – the obvious
   • Seq.fold – general aggregation
» Grouping elements of a sequence
   • Seq.groupBy – group using key
   • Seq.pairwise – adjacent pairs
   • Seq.windowed – sliding window
» For more see: http://fssnip.net/categories/Sequences
TASK #4
Find number of days when closing price is
larger than opening price by more than $5.



TASK #5
Calculate standard
deviation of the data
FSharpChart library

» Easy to use charting library for F#
   • Based on .NET 4.0 Chart Controls (WinForms/ASP.NET)
      Light-weight syntax
         for projections                    Line chart expects
                                           value or key * value
    [ for st in StockData.MSFT -> st.Date, st.Open ]
    |> FSharpChart.Line


» Designed to fit nicely with F#
    [ for st in StockData.MSFT -> st.Date, st.Open ]
    |> FSharpChart.Line
    |> FSharpChart.WithTitle
        ( Text = "Microsoft Stock Prices",
          Font = new System.Drawing.Font("Calibri", 16.0f) )
TASK #6
Create chart that shows values with 5 day average.
This can be done using Seq.windowed



TASK #7
Create chart that shows prices together with standard
deviation (over 5 day window) range
Processing data live and in parallel
» Observable                  » Parallel Sequence
  • Source generates data        • Parallel implementation
    (push-based model)           • Process large amount
  • Process data on-the-fly        of in-memory data
  • F# libs and .NET Rx          • Available in F# PowerPack

                                            In-memory, but
   prices |> Seq.windowed 100            processed in parallel
          |> PSeq.ordered
          |> PSeq.map averageAndSdv
                                                  Processing live
   pricesEvent |> Observable.windowed 100         data on the fly
               |> Observable.map averageAndSdv
Async Programming
The Problem


» Problems with I/O bound computations
   • Avoid blocking user interface
   • Handle many requests concurrently


» What needs to be done differently?
   • Avoid creating and blocking too many threads
   • Reliability and scalability are essential
   • React to events (from I/O or even GUI)
Using Explicit Callbacks

» Event-based programming model
     HttpServer.Start("http://localhost:8080/", fun ctx ->
       WebClient.DownloadAsync(getProxyUrl(ctx), fun data ->
         ctx.ResponseStream.WriteAsync(data, fun res ->
           ctx.ResponseStream.Close())))


   • Callback called when operation completes
   • Gaining popularity (e.g. Node.js)
» Does not solve all problems
   • Control structures don’t work (loops, try-catch, …)
   • Difficult to work with state
Synchronous to Asynchronous


» What would we want to write?
 let copyPageTo url outputStream = async {
   try
     let html ==WebClient.AsyncDownload(url)
     let! html   WebClient.AsyncDownload(url)
     outputStream.AsyncWrite(html)
     do! outputStream.AsyncWrite(html)
   finally
     ctx.ResponseStream.Close() }


» Turning synchronous to asynchronous
  • Wrap body in an async block
  • Asynchronous calls using do! and let!
  • Supports all F# control flow constructs
Async User Interfaces
Async GUI programming

» Controlling semaphore light
   • Using int or enum to keep current state?
   • Difficult to read – what does state represent?
» Better approach – asynchronous waiting
   • Loop switches between state
   • Asynchronous waiting for events


       green        orange         red
Writing loops using workflows

» Using standard language constructs

   let semaphoreStates() = async {
                                               Infinite loop!
     while true do
       for current in [ green; orange; red ] do
         let! md = Async.AwaitEvent(this.MouseDown)
         display(current) }
                                                  Wait for click
» Key idea – asynchronous waiting
   • F# events are first class values
   • Can use functional & imperative style
Checkout application workflow

» Think of a simple while loop
    Startup

                     Scan items

    Next customer                 Complete purchase

                    Print summary
Asynchronous and concurrent programming

» Asynchronous GUI in Checkout example
  • Single-threaded thanks to Async.StartImmediate
  • Easy way to encode control flow

» Parallel programming
  • Workflows are non-blocking computations
  • Run workflows in parallel with Async.Parallel

» Concurrent programming
  • Compose application from (thousands of) agents
  • Agents communicate using messages
Summary

» FP is already in the mainstream
» FP languages are ready
» Start small, go big
   •   Language Orientated Programming
   •   Exploratory and Scripting
   •   Asynchronous & Concurrency
   •   Technical Computing
   •   Testing
Summary
ICFP 2011
Meet the F#ers



       @rickasaurus

        @tomaspetricek

       @dmohl
F# Books
On the horizon

» http://functional-programming.net

                        http://meetup.com/fsharplondon
                        Every 6 weeks @ Skills Matter
Q&A


» http://Fsharp.net
» http://fssnip.net
» http://tomasp.net/blog
» http://trelford.com/blog

More Related Content

What's hot

Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Philip Schwarz
 
Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Bryan O'Sullivan
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskellgoncharenko
 
Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Bryan O'Sullivan
 
Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Philip Schwarz
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In ScalaKnoldus Inc.
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Philip Schwarz
 
Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Bryan O'Sullivan
 
A brief introduction to lisp language
A brief introduction to lisp languageA brief introduction to lisp language
A brief introduction to lisp languageDavid Gu
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data scienceJohn Cant
 
Introduction To Lisp
Introduction To LispIntroduction To Lisp
Introduction To Lispkyleburton
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaVladimir Kostyukov
 
Making an Object System with Tcl 8.5
Making an Object System with Tcl 8.5Making an Object System with Tcl 8.5
Making an Object System with Tcl 8.5Donal Fellows
 
Advance LISP (Artificial Intelligence)
Advance LISP (Artificial Intelligence) Advance LISP (Artificial Intelligence)
Advance LISP (Artificial Intelligence) wahab khan
 
Linear regression with R 2
Linear regression with R 2Linear regression with R 2
Linear regression with R 2Kazuki Yoshida
 

What's hot (20)

Functional programming
Functional programmingFunctional programming
Functional programming
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
 
Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Real World Haskell: Lecture 5
Real World Haskell: Lecture 5
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
 
Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2
 
Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Sequence and Traverse - Part 3
Sequence and Traverse - Part 3
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2
 
Monads do not Compose
Monads do not ComposeMonads do not Compose
Monads do not Compose
 
Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Real World Haskell: Lecture 3
Real World Haskell: Lecture 3
 
A brief introduction to lisp language
A brief introduction to lisp languageA brief introduction to lisp language
A brief introduction to lisp language
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
 
Introduction To Lisp
Introduction To LispIntroduction To Lisp
Introduction To Lisp
 
Python data handling notes
Python data handling notesPython data handling notes
Python data handling notes
 
Prolog & lisp
Prolog & lispProlog & lisp
Prolog & lisp
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 
Making an Object System with Tcl 8.5
Making an Object System with Tcl 8.5Making an Object System with Tcl 8.5
Making an Object System with Tcl 8.5
 
Advance LISP (Artificial Intelligence)
Advance LISP (Artificial Intelligence) Advance LISP (Artificial Intelligence)
Advance LISP (Artificial Intelligence)
 
Linear regression with R 2
Linear regression with R 2Linear regression with R 2
Linear regression with R 2
 

Viewers also liked

Word press getting started
Word press getting startedWord press getting started
Word press getting startedsdchandl
 
What does Yeshua have to teach me about prayer
What does Yeshua have to teach me about prayerWhat does Yeshua have to teach me about prayer
What does Yeshua have to teach me about prayerRichard Harvey
 
Autobiography.Pppowet
Autobiography.PppowetAutobiography.Pppowet
Autobiography.Pppowetguestdb05fc5
 
Clean up your code with C#6
Clean up your code with C#6Clean up your code with C#6
Clean up your code with C#6Rui Carvalho
 
Simplicity - develop modern web apps with tiny frameworks and tools
Simplicity - develop modern web apps with tiny frameworks and toolsSimplicity - develop modern web apps with tiny frameworks and tools
Simplicity - develop modern web apps with tiny frameworks and toolsRui Carvalho
 
Feedback Loops v4x3 Lightening
Feedback Loops v4x3 Lightening Feedback Loops v4x3 Lightening
Feedback Loops v4x3 Lightening Rui Carvalho
 

Viewers also liked (8)

Word press getting started
Word press getting startedWord press getting started
Word press getting started
 
What does Yeshua have to teach me about prayer
What does Yeshua have to teach me about prayerWhat does Yeshua have to teach me about prayer
What does Yeshua have to teach me about prayer
 
Autobiography.Pppowet
Autobiography.PppowetAutobiography.Pppowet
Autobiography.Pppowet
 
Code Cooking
Code Cooking Code Cooking
Code Cooking
 
Clean up your code with C#6
Clean up your code with C#6Clean up your code with C#6
Clean up your code with C#6
 
Simple Code
Simple CodeSimple Code
Simple Code
 
Simplicity - develop modern web apps with tiny frameworks and tools
Simplicity - develop modern web apps with tiny frameworks and toolsSimplicity - develop modern web apps with tiny frameworks and tools
Simplicity - develop modern web apps with tiny frameworks and tools
 
Feedback Loops v4x3 Lightening
Feedback Loops v4x3 Lightening Feedback Loops v4x3 Lightening
Feedback Loops v4x3 Lightening
 

Similar to FP Day 2011 - Turning to the Functional Side (using C# & F#)

F# Eye For The C# Guy - Seattle 2013
F# Eye For The C# Guy - Seattle 2013F# Eye For The C# Guy - Seattle 2013
F# Eye For The C# Guy - Seattle 2013Phillip Trelford
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Jesper Kamstrup Linnet
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from javaIndicThreads
 
Kotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platformsKotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platformsKirill Rozov
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmersAlexander Varwijk
 
Testing for share
Testing for share Testing for share
Testing for share Rajeev Mehta
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for KotlinTechMagic
 

Similar to FP Day 2011 - Turning to the Functional Side (using C# & F#) (20)

F# Eye For The C# Guy - Seattle 2013
F# Eye For The C# Guy - Seattle 2013F# Eye For The C# Guy - Seattle 2013
F# Eye For The C# Guy - Seattle 2013
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
C# programming
C# programming C# programming
C# programming
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Kotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platformsKotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platforms
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmers
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
 
Testing for share
Testing for share Testing for share
Testing for share
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Python basic
Python basicPython basic
Python basic
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 

More from Phillip Trelford

How to be a rock star developer
How to be a rock star developerHow to be a rock star developer
How to be a rock star developerPhillip Trelford
 
FSharp eye for the Haskell guy - London 2015
FSharp eye for the Haskell guy - London 2015FSharp eye for the Haskell guy - London 2015
FSharp eye for the Haskell guy - London 2015Phillip Trelford
 
Beyond lists - Copenhagen 2015
Beyond lists - Copenhagen 2015Beyond lists - Copenhagen 2015
Beyond lists - Copenhagen 2015Phillip Trelford
 
F# for C# devs - Copenhagen .Net 2015
F# for C# devs - Copenhagen .Net 2015F# for C# devs - Copenhagen .Net 2015
F# for C# devs - Copenhagen .Net 2015Phillip Trelford
 
Generative Art - Functional Vilnius 2015
Generative Art - Functional Vilnius 2015Generative Art - Functional Vilnius 2015
Generative Art - Functional Vilnius 2015Phillip Trelford
 
24 hours later - FSharp Gotham 2015
24 hours later - FSharp Gotham  201524 hours later - FSharp Gotham  2015
24 hours later - FSharp Gotham 2015Phillip Trelford
 
Building cross platform games with Xamarin - Birmingham 2015
Building cross platform games with Xamarin - Birmingham 2015Building cross platform games with Xamarin - Birmingham 2015
Building cross platform games with Xamarin - Birmingham 2015Phillip Trelford
 
Beyond Lists - Functional Kats Conf Dublin 2015
Beyond Lists - Functional Kats Conf Dublin 2015Beyond Lists - Functional Kats Conf Dublin 2015
Beyond Lists - Functional Kats Conf Dublin 2015Phillip Trelford
 
FSharp On The Desktop - Birmingham FP 2015
FSharp On The Desktop - Birmingham FP 2015FSharp On The Desktop - Birmingham FP 2015
FSharp On The Desktop - Birmingham FP 2015Phillip Trelford
 
Ready, steady, cross platform games - ProgNet 2015
Ready, steady, cross platform games - ProgNet 2015Ready, steady, cross platform games - ProgNet 2015
Ready, steady, cross platform games - ProgNet 2015Phillip Trelford
 
F# for C# devs - NDC Oslo 2015
F# for C# devs - NDC Oslo 2015F# for C# devs - NDC Oslo 2015
F# for C# devs - NDC Oslo 2015Phillip Trelford
 
F# for C# devs - Leeds Sharp 2015
F# for C# devs -  Leeds Sharp 2015F# for C# devs -  Leeds Sharp 2015
F# for C# devs - Leeds Sharp 2015Phillip Trelford
 
Build a compiler in 2hrs - NCrafts Paris 2015
Build a compiler in 2hrs -  NCrafts Paris 2015Build a compiler in 2hrs -  NCrafts Paris 2015
Build a compiler in 2hrs - NCrafts Paris 2015Phillip Trelford
 
24 Hours Later - NCrafts Paris 2015
24 Hours Later - NCrafts Paris 201524 Hours Later - NCrafts Paris 2015
24 Hours Later - NCrafts Paris 2015Phillip Trelford
 
Machine learning from disaster - GL.Net 2015
Machine learning from disaster  - GL.Net 2015Machine learning from disaster  - GL.Net 2015
Machine learning from disaster - GL.Net 2015Phillip Trelford
 
F# for Trading - QuantLabs 2014
F# for Trading -  QuantLabs 2014F# for Trading -  QuantLabs 2014
F# for Trading - QuantLabs 2014Phillip Trelford
 

More from Phillip Trelford (20)

How to be a rock star developer
How to be a rock star developerHow to be a rock star developer
How to be a rock star developer
 
Mobile F#un
Mobile F#unMobile F#un
Mobile F#un
 
F# eXchange Keynote 2016
F# eXchange Keynote 2016F# eXchange Keynote 2016
F# eXchange Keynote 2016
 
FSharp eye for the Haskell guy - London 2015
FSharp eye for the Haskell guy - London 2015FSharp eye for the Haskell guy - London 2015
FSharp eye for the Haskell guy - London 2015
 
Beyond lists - Copenhagen 2015
Beyond lists - Copenhagen 2015Beyond lists - Copenhagen 2015
Beyond lists - Copenhagen 2015
 
F# for C# devs - Copenhagen .Net 2015
F# for C# devs - Copenhagen .Net 2015F# for C# devs - Copenhagen .Net 2015
F# for C# devs - Copenhagen .Net 2015
 
Generative Art - Functional Vilnius 2015
Generative Art - Functional Vilnius 2015Generative Art - Functional Vilnius 2015
Generative Art - Functional Vilnius 2015
 
24 hours later - FSharp Gotham 2015
24 hours later - FSharp Gotham  201524 hours later - FSharp Gotham  2015
24 hours later - FSharp Gotham 2015
 
Building cross platform games with Xamarin - Birmingham 2015
Building cross platform games with Xamarin - Birmingham 2015Building cross platform games with Xamarin - Birmingham 2015
Building cross platform games with Xamarin - Birmingham 2015
 
Beyond Lists - Functional Kats Conf Dublin 2015
Beyond Lists - Functional Kats Conf Dublin 2015Beyond Lists - Functional Kats Conf Dublin 2015
Beyond Lists - Functional Kats Conf Dublin 2015
 
FSharp On The Desktop - Birmingham FP 2015
FSharp On The Desktop - Birmingham FP 2015FSharp On The Desktop - Birmingham FP 2015
FSharp On The Desktop - Birmingham FP 2015
 
Ready, steady, cross platform games - ProgNet 2015
Ready, steady, cross platform games - ProgNet 2015Ready, steady, cross platform games - ProgNet 2015
Ready, steady, cross platform games - ProgNet 2015
 
F# for C# devs - NDC Oslo 2015
F# for C# devs - NDC Oslo 2015F# for C# devs - NDC Oslo 2015
F# for C# devs - NDC Oslo 2015
 
F# for C# devs - Leeds Sharp 2015
F# for C# devs -  Leeds Sharp 2015F# for C# devs -  Leeds Sharp 2015
F# for C# devs - Leeds Sharp 2015
 
Build a compiler in 2hrs - NCrafts Paris 2015
Build a compiler in 2hrs -  NCrafts Paris 2015Build a compiler in 2hrs -  NCrafts Paris 2015
Build a compiler in 2hrs - NCrafts Paris 2015
 
24 Hours Later - NCrafts Paris 2015
24 Hours Later - NCrafts Paris 201524 Hours Later - NCrafts Paris 2015
24 Hours Later - NCrafts Paris 2015
 
Real World F# - SDD 2015
Real World F# -  SDD 2015Real World F# -  SDD 2015
Real World F# - SDD 2015
 
F# for C# devs - SDD 2015
F# for C# devs - SDD 2015F# for C# devs - SDD 2015
F# for C# devs - SDD 2015
 
Machine learning from disaster - GL.Net 2015
Machine learning from disaster  - GL.Net 2015Machine learning from disaster  - GL.Net 2015
Machine learning from disaster - GL.Net 2015
 
F# for Trading - QuantLabs 2014
F# for Trading -  QuantLabs 2014F# for Trading -  QuantLabs 2014
F# for Trading - QuantLabs 2014
 

Recently uploaded

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 

Recently uploaded (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

FP Day 2011 - Turning to the Functional Side (using C# & F#)

  • 1. Turning to the Functional side (Using C# and F#) Phil Trelford Tomas Petricek http://trelford.com/blog http://tomasp.net/blog @ptrelford @tomaspetricek
  • 2. About Us » Tomas • Author of F# book for C# programmers • Worked with the F# team at Microsoft • First blogged about F# in May 2006 » Phil • Software Developer and Architect • Worked on first F# applications at Microsoft • Co-organizer of London F# User Group » http://functional-programming.net
  • 3. Tutorial Goals » Introduce Functional Concepts with F# and C# Non-goals » Provide in-depth understanding » Mass conversion to functional programming cult » Sell books
  • 6. The F in F# stands for FUN
  • 7. Halo 3 with F# Skills
  • 8. XBLA: Path to Go – F# AI
  • 9. F# » Strongly Typed » Functional » Object Orientated » Open Source » .Net language » In Visual Studio
  • 10. Functional Programing » Pure Functions » Higher Order Functions » Pattern Matching
  • 12. Higher Order Functions F# Map/Reduce C# Map/Reduce let map f xs = seq { public static IEnumerable<R> Map<T, R> for x in xs do (this IEnumerable<T> xs, Func<T, R> f) yield f x { foreach (var x in xs) } yield return f(x); } let reduce f init items = public static R Reduce<T, R> let mutable current = init (this IEnumerable<T> xs, R init, for item in items do Func<R, T, R> f) { current <- f current item var current = init; foreach (var x in xs) current current = f(current, x); return current; }
  • 13. Pattern Matching F# C# match day with switch (day) { | 0 -> "Sunday" case 0: return "Sunday"; case 1: return "Monday"; | 1 -> "Monday" case 2: return "Tuesday"; | 2 -> "Tuesday" case 3: return "Wednesday"; case 4: return "Thursday"; | 3 -> "Wednesday" case 5: return "Friday"; | 4 -> "Thursday" case 6: return "Saturday"; default: | 5 -> "Friday" throw new ArgumentException("day"); | 6 -> "Saturday" } | _ –> invalidArg "Invalid day"
  • 14. Light Syntax F# C# public class Person type Person(name:string,age:int) = { public Person(string name, int age) /// Full name { _name = name; member person.Name = name _age = age; } /// Age in years private readonly string _name; member person.Age = age private readonly int _age; /// <summary> /// Full name /// </summary> public string Name { get { return _name; } } /// <summary> /// Age in years /// </summary> public int Age { get { return _age; } } }
  • 15. Functional data structures » A way of thinking about problems » Model data using composition of primitives Tuple Combine two values of different types Discriminated Represents one of several options Union List Zero or more values of the same type
  • 16. Tuples: Containers for a few different things
  • 18. Representing event schedule Object-oriented way Functional way Schedule Schedule Tag : ScheduleType GetNextOccurrence() : DateTime Once Never Repeatedly Once Never Repeatedly » Easy to add new cases » Easy to add new functions » Hard to add new functions » Hard to add new cases » Good thing about F# and Scala – you can use both!
  • 19. Cutting the caterpillar Head Head Head Head Head End!
  • 20. Functional Lists in C# » List is either empty or nonempty List Nonempty Empty (head, tail) • In C#, a class hierarchy with two classes • In F#, a discriminated union with two cases
  • 21. Functional lists in C# public class FunctionalList<T> { // Creates a new list that is empty public FunctionalList(); // Creates a non-empty list public FunctionalList(T head, FunctionalList<T> tail); // Is the list empty? public bool IsEmpty { get; } // Properties valid for a non-empty list public T Head { get; } public FunctionalList<T> Tail { get; } }
  • 22. Domain Modelling » Retail Domain -> Testing » http://tomasp.net/fpday.zip
  • 24. Yahoo Stock Prices » Data stored in a CSV file Date,Open,High,Low,Close,Volume,Adj Close 2011-10-12,407.34,409.25,400.14,402.19,22206600,402.19 2011-10-11,392.57,403.18,391.50,400.29,21609800,400.29 2011-10-10,379.09,388.81,378.21,388.81,15769200,388.81 » Read and print all data open System.IO let dir = __SOURCE_DIRECTORY__ + "dataaapl.csv" let lines = File.ReadAllLines(dir) for line in lines do printfn "%s" line
  • 25. Parsing CSV data » Get some data for testing let line1 = lines |> Seq.head let line2 = lines |> Seq.skip 1 |> Seq.head » Using arrays in F# let arr = str.Split([| ',' |]) arr.[0] » Converting strings to numbers float "12.34" DateTime.Parse("1985-05-02")
  • 26. TASK #1 Iterate over lines, parse CSV and print date & price
  • 27. Sequence expressions » Exploring data using imperative loops for year, value in yearlyAverages do if value < 25.0 then printfn "%d (only %f)" year value » Can be turned into a sequence expression… let badYears = seq { for year, value in yearlyAverages do if value < 25.0 then yield year, value } • Result has a type seq<int * float> (IEnumerable) • Brackets: [| … |] for arrays, [ … ] for lists, set [ … ] for sets
  • 28. TASK #2 Turn the parsing into a sequence expression
  • 29. Organizing Source Code » Compiled Libraries • Allow C# users call F# code • Encapsulate (complete) functionality » F# Script Files • Great for explorative programming • Script can load some other files // File1.fsx // File2.fsx module StockData #load "File1.fsx" open StockData let getData name = name, 99.0 getData "MSFT"
  • 30. TASK #3 Write function that parses specified CSV file
  • 31. Processing Data in F# » Writing data processing query in F# Lambda function All types are inferred StockData.MSFT |> Seq.filter (fun stock -> stock.Close - stock.Open > 7.0) |> Seq.map (fun stock -> stock.Date) |> Seq.iter (printfn "%A") Partial function application Custom operators » Seq module provides functions for IEnumerable • But some operations make only sense for arrays/lists » Sequence expressions provide query-like syntax
  • 32. Useful functions » Basic Functions • Seq.filter – filter elements using predicate (aka Where) • Seq.map – turn values into different (aka Select) » Aggregating all elements of a sequence • Seq.max, Seq.min, Seq.averag – the obvious • Seq.fold – general aggregation » Grouping elements of a sequence • Seq.groupBy – group using key • Seq.pairwise – adjacent pairs • Seq.windowed – sliding window » For more see: http://fssnip.net/categories/Sequences
  • 33. TASK #4 Find number of days when closing price is larger than opening price by more than $5. TASK #5 Calculate standard deviation of the data
  • 34. FSharpChart library » Easy to use charting library for F# • Based on .NET 4.0 Chart Controls (WinForms/ASP.NET) Light-weight syntax for projections Line chart expects value or key * value [ for st in StockData.MSFT -> st.Date, st.Open ] |> FSharpChart.Line » Designed to fit nicely with F# [ for st in StockData.MSFT -> st.Date, st.Open ] |> FSharpChart.Line |> FSharpChart.WithTitle ( Text = "Microsoft Stock Prices", Font = new System.Drawing.Font("Calibri", 16.0f) )
  • 35. TASK #6 Create chart that shows values with 5 day average. This can be done using Seq.windowed TASK #7 Create chart that shows prices together with standard deviation (over 5 day window) range
  • 36. Processing data live and in parallel » Observable » Parallel Sequence • Source generates data • Parallel implementation (push-based model) • Process large amount • Process data on-the-fly of in-memory data • F# libs and .NET Rx • Available in F# PowerPack In-memory, but prices |> Seq.windowed 100 processed in parallel |> PSeq.ordered |> PSeq.map averageAndSdv Processing live pricesEvent |> Observable.windowed 100 data on the fly |> Observable.map averageAndSdv
  • 38. The Problem » Problems with I/O bound computations • Avoid blocking user interface • Handle many requests concurrently » What needs to be done differently? • Avoid creating and blocking too many threads • Reliability and scalability are essential • React to events (from I/O or even GUI)
  • 39. Using Explicit Callbacks » Event-based programming model HttpServer.Start("http://localhost:8080/", fun ctx -> WebClient.DownloadAsync(getProxyUrl(ctx), fun data -> ctx.ResponseStream.WriteAsync(data, fun res -> ctx.ResponseStream.Close()))) • Callback called when operation completes • Gaining popularity (e.g. Node.js) » Does not solve all problems • Control structures don’t work (loops, try-catch, …) • Difficult to work with state
  • 40. Synchronous to Asynchronous » What would we want to write? let copyPageTo url outputStream = async { try let html ==WebClient.AsyncDownload(url) let! html WebClient.AsyncDownload(url) outputStream.AsyncWrite(html) do! outputStream.AsyncWrite(html) finally ctx.ResponseStream.Close() } » Turning synchronous to asynchronous • Wrap body in an async block • Asynchronous calls using do! and let! • Supports all F# control flow constructs
  • 42. Async GUI programming » Controlling semaphore light • Using int or enum to keep current state? • Difficult to read – what does state represent? » Better approach – asynchronous waiting • Loop switches between state • Asynchronous waiting for events green orange red
  • 43. Writing loops using workflows » Using standard language constructs let semaphoreStates() = async { Infinite loop! while true do for current in [ green; orange; red ] do let! md = Async.AwaitEvent(this.MouseDown) display(current) } Wait for click » Key idea – asynchronous waiting • F# events are first class values • Can use functional & imperative style
  • 44. Checkout application workflow » Think of a simple while loop Startup Scan items Next customer Complete purchase Print summary
  • 45. Asynchronous and concurrent programming » Asynchronous GUI in Checkout example • Single-threaded thanks to Async.StartImmediate • Easy way to encode control flow » Parallel programming • Workflows are non-blocking computations • Run workflows in parallel with Async.Parallel » Concurrent programming • Compose application from (thousands of) agents • Agents communicate using messages
  • 46. Summary » FP is already in the mainstream » FP languages are ready » Start small, go big • Language Orientated Programming • Exploratory and Scripting • Asynchronous & Concurrency • Technical Computing • Testing
  • 49. Meet the F#ers @rickasaurus @tomaspetricek @dmohl
  • 51. On the horizon » http://functional-programming.net http://meetup.com/fsharplondon Every 6 weeks @ Skills Matter
  • 52. Q&A » http://Fsharp.net » http://fssnip.net » http://tomasp.net/blog » http://trelford.com/blog

Editor's Notes

  1. Thoughtworkstechnlogy radar: http://www.thoughtworks.com/radar/Image source: http://www.thoughtworks.com/sites/www.thoughtworks.com/files/files/tw-radar-april-2010.pdfSee also: http://qconlondon.com/london-2010/file?path=/qcon-london-2010/slides/AmandaLaucher_and_JoshGraham_TheStateOfTheArtNET12MonthsOfThingsToLearn.pdf