Share
Embed
RecurSD: Intro to FSharp
Presentation used for the RecurSD (the Functional Programming Conference in San Diego, CA) on January 18th 2014.
César López-Natarén
January 18, 2014
Transcript
25 slides
-
WHAT IS F#? Functional programming language (that also supports object-
oriented and imperative programming) Created by at Microsoft Research Production quality compiler, tools, libraries, and support Full blown project and ecosystem The core of the language was inspired by and code runs in the .NET framework Extended to be a first class language in the Don Syme Open Source OCaml CLI -
WHAT IS FUNCTIONAL PROGRAMMING? A programming style which utilizes higher
order functions and minimizes effects on FP -
HIGHER ORDER FUNCTIONS IN F# let toThePower xs power =
Seq.map power xs let squares = toThePower [1; 2; 3; 4] (fun x -> x * x) let cubes = toThePower [1; 2; 3; 4] (fun x -> x * x * x) -
HOF IN F# (2) let (|>) x f = f
x let toThePower xs power = Seq.map power xs let xs = toThePower [1; 2; 3; 4] let squares = (fun x -> x * x) |> xs let cubes = (fun x -> x * x * x) |> xs -
HOF IN F# (3) let squaredEvens = [1; 2; 3;
4] |> Seq.filter (fun x -> x % 2 = 0) |> Seq.map (fun x -> x * x) |> Seq.sum -
MINIMIZING EFFECTS In all of the previous examples, the original
data structure was never modified let myList = [1; 2; 3; 4; 5] let newList = myList |> Seq.map (fun x -> x + 2) |> Seq.toList myList newList -
MINIMIZING EFFECTS (2) type User = { FirstName : string;
LastName : string; } let johnDoe = { FirstName = "John"; LastName = "Doe" } let johnSmit = { johnDoe with LastName = "Smith" } -
MINIMIZING ERRORS Discriminated Unions type Option<'a> = | Some of
'a | None let printKind something = match something with | Some x -> x.GetType().Name -
MINIMIZING ERRORS (2) type Person(name : string) = member this.Name
= name let printName (p : Person) = printfn "%s" p.Name printName (Person "Haskell Curry") printName null -
SO FAR WE HAVE SEEN Higher order functions enable the
creation of abstractions that compose Limiting side effects let us have a simpler mental (and real) execution model for our programs -
SEQUENCES Unified way to work with collections Based on the
interface, abbreviated as in F# Declarative way to express: Collections creation Aggregation Iteration -
RANGE SEQUENCE EXPRESSIONS seq { 1 .. 10 } seq
{ -34.0 .. -30.0 } seq { 1.0 .. 3.3 .. 20.0 } -
SEQ EXAMPLE open System.IO let rec allFiles dir = Seq.append
(dir |> Directory.GetFiles) (dir |> Directory.GetDirectories |> Seq.map allFiles |> Seq.concat) allFiles "/sbin" |> Seq.map (fun filename -> (filename.Length, filename)) |> Seq.sortBy (fun t -> (fst t)) |> Seq.take(10) |> Seq.toArray -
ASYNCHRONOUS WORKFLOWS Unified and declarative way to work with asynchronous
computations Does not block a thread when I/O happens Sleeps happen Or other async operation is scheduled Based on the Async<'T> type at its core Which represents a value of type 'T at some point in the future Preserves the readability of synchronous code (avoid nested callbacks -
ASYNC WORKFLOWS open System.Net open Microsoft.FSharp.Control.WebExtensions let tprintfn fmt =
printf "[Thread %d]" System.Threading.Thread.CurrentThread.ManagedThreadId; printfn fmt let urlList = [ "Wikipedia", "http://www.wikipedia.org" "The Times", "http://www.nytimes.com" "Le Monde", "http://www.lemonde.fr" ] let fetchAsync(name, url:string) = async { try let uri = new System.Uri(url) let webClient = new WebClient() let! html = webClient.AsyncDownloadString(uri) tprintfn "Read %d characters for %s" html.Length name with | ex -> tprintfn "%s" (ex.Message); } urlList |> Seq.map fetchAsync |> Async.Parallel |> Async.RunSynchronously |> ignore -
AS YOU MIGHT HAVE NOTICED Sequences and Async workflows (&
query expressions, which I didn't show you) have a common "shape" They are generally known as Computation Expressions You can define your own! Create a builder type Implement the special methods that define how the fragments of the computation are combined: Bind Return Zero etc -
F# MAIN BENEFITS Strong static types without being verbose Type
inference Concise syntax Awesome support for functional programming Less typing, more thinking, yields correct code -
REAL WORLD USAGE web framework distributed computations data and time
series manipulation library Prevalent usage in the financial services industry and case studies WebShaper {m}brace Deedle Testimonials -
RESOURCES @ Twitter Talk " " by Don Syme Fsharp.Org
FSharp for fun and profit Visual F# FSharp code snippets #fsharp F# in the open source world Books