Introduction to F#


Published on

Introduction to F# for the New England Visual Basic Professionals User Group.

Published in: Technology

Introduction to F#

  1. 1. Introduction to F#<br />Talbott Crowell<br />
  2. 2. Functional programming has been around a long time<br />Not new<br />Long history<br />Functional programming is safe<br />A concern as we head toward manycore and cloud computing<br />Functional programming is on the rise<br />Why another language?<br />
  3. 3. 1930’s: lambda calculus (roots)<br />1956: IPL (Information Processing Language) “the first functional language<br />1958: LISP “a functional flavored language”<br />1962: APL (A Programming Language)<br />1973: ML (Meta Language)<br />1983: SML (Standard ML)<br />1987: Caml (Categorical Abstract Machine Language ) and Haskell<br />1996: OCaml (Objective Caml)<br />Functional programming has been around a long time<br />
  4. 4. Side effects<br />Modifies some state<br />Has observable interaction with calling functions <br />Has observable interaction with the outside world<br />Example: a function or method with no return value<br />Most functional languages encourage programmers to avoid side effects<br />Haskell (a “pure” functional language) restricts side effects with a static type system<br />Functional programming is safe<br />
  5. 5. Language Evolution (Simon Payton-Jones)<br />C#, VB, Java, C are imperative programming languages. Very useful but can change the state of the world at anytime creating side effects.<br />Nirvana! Useful and Safe<br />F#<br />Haskell is Very Safe, but not very useful. Used heavily in research and academia, but rarely in business .<br /><br />
  6. 6. Long relegated to academia<br />Industrial and commercial applications<br />Scheme, Erlang, OCaml, Haskell<br />F# at Grange Insurance, Ohio:<br />F# used by XBox Live Trueskill:<br />DSL’s<br />Mathematica<br />XSLT<br />Excel can be viewed as a functional programming language<br />Functional programming on the rise<br />
  7. 7. Functional language developed by Microsoft Research<br />By Don Syme and his team, who productized Generics<br />Based on OCaml (influenced by C# and Haskell)<br />History<br />2002: F# language design started<br />2005 January: F# 1.0.1 releases to public<br />Not a product. Integration with VS2003<br />Works in .NET 1.0 through .NET 2.0 beta, Mono<br />2005 November: F# 1.1.5 with VS 2005 RTM support<br />2009 October: VS2010 Beta 2, CTP for VS2008 & Non-Windows users<br />2010: F# is “productized” and baked into VS 2010<br />What is F#<br />
  8. 8. Interactive Scripting<br />Good for prototyping<br />Succinct = Less code<br />Type Inference<br />Strongly typed, strict<br />Automatic generalization (generics for free)<br />Few type annotations<br />1st class functions (currying, lazy evaluations)<br />Pattern matching<br />Key Characteristics of F#<br />
  9. 9. Multi-Paradigm<br />Functional Programming<br />Imperative Programming<br />Object Oriented Programming<br />Language Oriented Programming<br />Task Oriented Programming<br />F# is not just Functional<br />
  10. 10. Dynamically compiles code on the fly<br />Example:<br />Demo<br />F# Interactive<br />open System.Drawing;; <br />open System.Windows.Forms;; <br />let myform = new Form(Text=&quot;Hello Everybody&quot;, Visible=true);; <br />myform.BackColor &lt;- Color.Blue;;<br />let mybutton = new Button(Text = &quot;Click Me&quot;);;<br />myform.Controls.Add(mybutton);; <br />mybutton.BackColor &lt;- Color.White;; <br />mybutton.Click.Add(fun _ -&gt; MessageBox.Show(&quot;Clicked&quot;) |&gt; ignore);;<br />
  11. 11. Type inference<br />Expressions<br />F# Basics<br />let x = 5<br />let y = 5.0 <br />let files = Directory.GetFiles(@&quot;C:imagesoriginal&quot;)<br />let x = 5 * 5<br />let y = 5.0 / 3.0<br />let width = image.Width / 8 <br />
  12. 12. Function<br />Anonymous functions<br />F# Functions<br />let sqr x = x * x<br />sqr 5<br />(fun x -&gt; x * x) 5 <br />
  13. 13. The |&gt; Combinator “Pipe Forward”<br /> Example<br />F# Combinators<br /> x |&gt; f is the same as f x<br /> let sqr x = x * x<br />sqr x<br /> 5 |&gt; sqr<br />
  14. 14. Partial functions<br />Don’t have to pass all parameters at once<br />Curried Functions<br />letDivideBy y x = x / y<br />let result = DivideBy 2.0 3.0<br />valDivideBy : float -&gt; float -&gt; float<br />val result : float = 1.5<br />let HalfOf = DivideBy 2.0<br />let result2 = HalfOf 3.0<br />valHalfOf : (float -&gt; float)<br />val result2 : float = 1.5<br />
  15. 15. Pass curried function to another function<br />Power of Curried Functions<br />letDivideBy y x = x / y<br />letnumbers = [1.0; 2.0; 3.0]<br />let result3 = (DivideBy 2.0) numbers<br />valDivideBy : float -&gt; float -&gt; float<br />val numbers : float list = [1.0; 2.0; 3.0]<br />val result3 : float list = [0.5; 1.0; 1.5]<br />
  16. 16. Compare with VB<br />Function DivideBy(ByVal y As Single, _<br />ByVal x As Single) As Single<br /> Return x / y<br />End Function<br />Sub Main()<br /> Dim numbers = New Single() {1.0, 2.0, 3.0}<br /> Dim result3 As New List(Of Single)<br /> For Each number In numbers<br /> result3.Add(DivideBy(2.0, number))<br /> Next<br />End Sub<br />
  17. 17. used to group values together without creating a class or struct<br />Tuple<br />Tuple as a function parameter<br />#light<br />open System<br />let swap (x, y) = (y, x)<br />let rotate (x, y, z) = (y, z, x)<br />let circleDetails radius =<br /> let area = Math.PI * (radius * radius)<br /> let circumference = 2.0 * Math.PI * radius<br /> (area, circumference)<br />let result1 = swap(3, 2)<br />let result2 = rotate(5, 6, 7)<br />let details = circleDetails 4.0<br />let (a, c) = details<br />Tuple as a return value<br />Tuple as left side of an assignment<br />
  18. 18. Similar to Object Oriented inheritance<br />Useful in pattern matching<br />Discriminated Unions<br />type Suit =<br /> | Spades<br /> | Hearts<br /> | Clubs<br /> | Diamonds<br />let suits = [Spades; Hearts; Clubs; Diamonds]<br />
  19. 19. Discriminated Unions cont.<br />type Suit =<br /> | Spades<br /> | Hearts<br /> | Clubs<br /> | Diamonds<br />type Card =<br /> | Ace of Suit<br /> | RankCard of int * Suit<br /> | Jack of Suit<br /> | Queen of Suit<br /> | King of Suit<br /> | Joker<br />let card1 = Ace(Diamonds)<br />let card2 = RankCard(3, Spades)<br />let card3 = Joker<br />
  20. 20. Used often in F# programs<br />Syntax (source: )<br />Pattern Matching<br />
  21. 21. Mouse event handler in DirectX Demo<br />Checking mouse button and shift key modifiers<br />Pattern Matching Example<br />match b.Button, Form.ModifierKeys with <br /> | MouseButtons.Left, Keys.Shift -&gt; view.AdjustZoom(dx,dy)<br /> | MouseButtons.Left, _ -&gt; view.AdjustYawPitchRoll(dx,dy)<br /> | _ -&gt; view.AdjustFocus(dx,dy) <br />
  22. 22. FSharp Samples v0.2 <br />The DirectX Demo<br />More F# Interactive<br /><br />
  23. 23. The Power Wall<br />Manycore FUD<br />Free lunch is over<br />Parallel programming in .NET<br />Where F# fits into this future<br />F# and Impact on the Future<br />
  24. 24. The Power Wall: CPU Clock Speed<br />From Katherine Yelick’s “Multicore: Fallout of a Hardware Revolution”<br />
  25. 25. Fear, Uncertainty, and Doubt<br />Talbott’s FUD slide: why you should be concerned<br />Moore’s Law<br />Predicted in 1965 that transistor density in semiconductor chips would double every 18 months<br />Clock speed on chips plateaued in 2005 at 3 GHz due to the “Power Wall”<br />Intel and AMD have now begun doubling cores every 18 months to keep up with Moore’s Law<br />AMD Opteron Istanbul and Intel Xeon have 6 cores per socket used in Servers<br />Dell Studio XPS (2009 price of $750) comes with Intel i7 with 4 cores with 2 way hyper-threading (8 virtual cores)<br />Intel Larrabee on the horizon with 32 cores with 4 way hyper-threading (128 virtual cores)<br />FUD<br />
  26. 26. Source: Wikipedia entry for Larrabee (GPU)<br />Intel Larrabee<br />
  27. 27. Free lunch is over<br />Programs are not doubling in speed every couple of years for free anymore<br />We need to start writing code to take advantage of many cores<br />Currently painful and problematic to take advantage of many cores because of shared memory, locking, and other imperative programming techniques<br />Problem<br />
  28. 28. Libraries and Framework Improvements<br />TPL (Included in .NET 4.0)<br />PLINQ<br />Programming Approaches<br />Functional programming<br />Immutable data<br />No side effects<br />Task oriented programming<br />Solution<br />
  29. 29. Parallel Programming in the .NET Framework 4 Beta 2<br />
  30. 30. “F# is, technically speaking, neutral with respect to concurrency - it allows the programmer to exploit the many different techniques for concurrency and distribution supported by the .NET platform” <br />F# FAQ:<br />Functional programming is a primary technique for minimizing/isolating mutable state<br />Asynchronous workflows make writing parallel programs in a “natural and compositional style”<br />F# and Multi-Core Programming<br />
  31. 31. Problem<br />Resize a ton of images<br />Demo of Image Processor<br />let files = Directory.GetFiles(@&quot;C:imagesoriginal&quot;)<br />for file in files do<br /> use image = Image.FromFile(file)<br /> use smallImage = ResizeImage(image)<br /> let destFileName = DestFileName(&quot;s1&quot;, file)<br />smallImage.Save(destFileName)<br />
  32. 32. Asynchronous Workflows<br />let FetchAsync(file:string) =<br />async {<br /> use stream = File.OpenRead(file)<br /> let! bytes = stream.AsyncRead(intstream.Length)<br /> use memstream = new MemoryStream(bytes.Length)<br />memstream.Write(bytes, 0, bytes.Length)<br /> use image = Image.FromStream(memstream)<br /> use smallImage = ResizeImage(image)<br /> let destFileName = DestFileName(&quot;s2&quot;, file)<br />smallImage.Save(destFileName)<br /> }<br />let tasks = [for file in files -&gt; FetchAsync(file)]<br />let parallelTasks = Async.Parallel tasks<br />Async.RunSynchronouslyparallelTasks<br />
  33. 33. Almost 2x on 2 cores<br />About 3.5x faster on 8 cores<br />Demo Asynchronous Workflow<br />
  34. 34. Thank you for attending Intro to F#Questions?<br />F# User Group<br /><br />Twitter: @FSUG<br />Talbott Crowell,<br /><br />Twitter: @Talbott<br />
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.