Turning to the Functional side                (Using C# and F#)    Phil Trelford           Tomas Petricekhttp://trelford.c...
About Us» Tomas   • Author of F# book for C# programmers   • Worked with the F# team at Microsoft   • First blogged about ...
TutorialGoals» Introduce Functional Concepts with F# and C#Non-goals» Provide in-depth understanding» Mass conversion to f...
Thoughtworks Technology Radar July 2011
Visual F#
The F in F# stands forFUN
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/Reducelet map f xs = seq {               public static    ...
Pattern MatchingF#                          C#match day with              switch (day) {| 0 -> "Sunday"               case...
Light SyntaxF#                                   C#                                     public class Persontype Person(nam...
Functional data structures» A way of thinking about problems» Model data using composition of primitives       Tuple      ...
Tuples: Containers for a few different things
Discriminated Unions: Exclusive alternatives
Representing event scheduleObject-oriented way                         Functional way                Schedule             ...
Cutting the caterpillar Head                     Head                                 Head          Head                  ...
Functional Lists in C#» List is either empty or nonempty                                 List                  Nonempty   ...
Functional lists in C# public class FunctionalList<T> {   // Creates a new list that is empty   public FunctionalList();  ...
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.1...
Parsing CSV data» Get some data for testing   let line1 = lines |> Seq.head   let line2 = lines |> Seq.skip 1 |> Seq.head»...
TASK #1Iterate 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 t...
TASK #2Turn the parsing into a sequence expression
Organizing Source Code» Compiled Libraries   • Allow C# users call F# code   • Encapsulate (complete) functionality» F# Sc...
TASK #3Write function that parses specified CSV file
Processing Data in F#» Writing data processing query in F#       Lambda function                   All types are inferred ...
Useful functions» Basic Functions   • Seq.filter – filter elements using predicate (aka Where)   • Seq.map – turn values i...
TASK #4Find number of days when closing price islarger than opening price by more than $5.TASK #5Calculate standarddeviati...
FSharpChart library» Easy to use charting library for F#   • Based on .NET 4.0 Chart Controls (WinForms/ASP.NET)      Ligh...
TASK #6Create chart that shows values with 5 day average.This can be done using Seq.windowedTASK #7Create chart that shows...
Processing data live and in parallel» Observable                  » Parallel Sequence  • Source generates data        • Pa...
Async Programming
The Problem» Problems with I/O bound computations   • Avoid blocking user interface   • Handle many requests concurrently»...
Using Explicit Callbacks» Event-based programming model     HttpServer.Start("http://localhost:8080/", fun ctx ->       We...
Synchronous to Asynchronous» What would we want to write? let copyPageTo url outputStream = async {   try     let html ==W...
Async User Interfaces
Async GUI programming» Controlling semaphore light   • Using int or enum to keep current state?   • Difficult to read – wh...
Writing loops using workflows» Using standard language constructs   let semaphoreStates() = async {                       ...
Checkout application workflow» Think of a simple while loop    Startup                     Scan items    Next customer    ...
Asynchronous and concurrent programming» Asynchronous GUI in Checkout example  • Single-threaded thanks to Async.StartImme...
Summary» FP is already in the mainstream» FP languages are ready» Start small, go big   •   Language Orientated Programmin...
Summary
ICFP 2011
Meet the F#ers       @rickasaurus        @tomaspetricek       @dmohl
F# Books
On the horizon» http://functional-programming.net                        http://meetup.com/fsharplondon                   ...
Q&A» http://Fsharp.net» http://fssnip.net» http://tomasp.net/blog» http://trelford.com/blog
Upcoming SlideShare
Loading in …5
×

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

3,298 views
3,191 views

Published on

Slides presented at FP Day 2011 in Cambridge

Published in: Technology
0 Comments
6 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,298
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
34
Comments
0
Likes
6
Embeds 0
No embeds

No notes for slide
  • 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
  • FP Day 2011 - Turning to the Functional Side (using C# & F#)

    1. 1. Turning to the Functional side (Using C# and F#) Phil Trelford Tomas Petricekhttp://trelford.com/blog http://tomasp.net/blog @ptrelford @tomaspetricek
    2. 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. 3. TutorialGoals» Introduce Functional Concepts with F# and C#Non-goals» Provide in-depth understanding» Mass conversion to functional programming cult» Sell books
    4. 4. Thoughtworks Technology Radar July 2011
    5. 5. Visual F#
    6. 6. The F in F# stands forFUN
    7. 7. Halo 3 with F# Skills
    8. 8. XBLA: Path to Go – F# AI
    9. 9. F#» Strongly Typed» Functional» Object Orientated» Open Source» .Net language» In Visual Studio
    10. 10. Functional Programing» Pure Functions» Higher Order Functions» Pattern Matching
    11. 11. Pure Functions - Excel
    12. 12. Higher Order Functions F# Map/Reduce C# Map/Reducelet 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. 13. Pattern MatchingF# 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. 14. Light SyntaxF# C# public class Persontype 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. 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. 16. Tuples: Containers for a few different things
    17. 17. Discriminated Unions: Exclusive alternatives
    18. 18. Representing event scheduleObject-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. 19. Cutting the caterpillar Head Head Head Head Head End!
    20. 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. 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. 22. Domain Modelling» Retail Domain -> Testing» http://tomasp.net/fpday.zip
    23. 23. Processing Stock Prices
    24. 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. 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. 26. TASK #1Iterate over lines, parse CSV and print date & price
    27. 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. 28. TASK #2Turn the parsing into a sequence expression
    29. 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. 30. TASK #3Write function that parses specified CSV file
    31. 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. 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. 33. TASK #4Find number of days when closing price islarger than opening price by more than $5.TASK #5Calculate standarddeviation of the data
    34. 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. 35. TASK #6Create chart that shows values with 5 day average.This can be done using Seq.windowedTASK #7Create chart that shows prices together with standarddeviation (over 5 day window) range
    36. 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
    37. 37. Async Programming
    38. 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. 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. 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
    41. 41. Async User Interfaces
    42. 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. 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. 44. Checkout application workflow» Think of a simple while loop Startup Scan items Next customer Complete purchase Print summary
    45. 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. 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
    47. 47. Summary
    48. 48. ICFP 2011
    49. 49. Meet the F#ers @rickasaurus @tomaspetricek @dmohl
    50. 50. F# Books
    51. 51. On the horizon» http://functional-programming.net http://meetup.com/fsharplondon Every 6 weeks @ Skills Matter
    52. 52. Q&A» http://Fsharp.net» http://fssnip.net» http://tomasp.net/blog» http://trelford.com/blog

    ×