Top Banner
Introduction to F# Talbott Crowell
34

Introduction to F#

May 10, 2015

Download

Technology

Talbott Crowell

Introduction to F# for the New England Visual Basic Professionals User Group.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to F#

Introduction to F#Talbott Crowell

Page 2: Introduction to F#

Functional programming has been around a long time Not new

Long history

Functional programming is safe A concern as we head toward manycore and cloud

computing

Functional programming is on the rise

Why another language?

Page 3: Introduction to F#

1930’s: lambda calculus (roots)

1956: IPL (Information Processing Language) “the first functional language

1958: LISP “a functional flavored language”

1962: APL (A Programming Language)

1973: ML (Meta Language)

1983: SML (Standard ML)

1987: Caml (Categorical Abstract Machine Language ) and Haskell

1996: OCaml (Objective Caml)

Functional programming has been around a long time

Page 4: Introduction to F#

Side effects Modifies some state

Has observable interaction with calling functions

Has observable interaction with the outside world

Example: a function or method with no return value

Most functional languages encourage programmers to avoid side effects

Haskell (a “pure” functional language) restricts side effects with a static type system

Functional programming is safe

Page 5: Introduction to F#

1 2 3 4 5 6 7 8 9 10 110

2

4

6

8

10

12

C#NirvanaHaskellLINQ

Safety

Usefulness

C#, VB, Java LINQ Nirvana

Haskell

Language Evolution (Simon Payton-Jones)

http://channel9.msdn.com/posts/Charles/Simon-Peyton-Jones-Towards-a-Programming-Language-Nirvana/

C#, VB, Java, C are imperative programming languages. Very useful but can change the state of the world at anytime creating side effects.

Nirvana! Useful

and Safe

Haskell is Very Safe, but not very useful. Used heavily in research and academia, but rarely in business .

F#

Page 6: Introduction to F#

Long relegated to academia

Industrial and commercial applications Scheme, Erlang, OCaml, Haskell

F# at Grange Insurance, Ohio: http://bit.ly/GrangeFSharp

F# used by XBox Live Trueskill: http://bit.ly/trueskill

DSL’s Mathematica

XSLT

Excel can be viewed as a functional programming language

Functional programming on the rise

Page 7: Introduction to F#

Functional language developed by Microsoft Research By Don Syme and his team, who productized Generics

Based on OCaml (influenced by C# and Haskell)

History 2002: F# language design started

2005 January: F# 1.0.1 releases to public Not a product. Integration with VS2003 Works in .NET 1.0 through .NET 2.0 beta, Mono

2005 November: F# 1.1.5 with VS 2005 RTM support

2009 October: VS2010 Beta 2, CTP for VS2008 & Non-Windows users

2010: F# is “productized” and baked into VS 2010

What is F#

Page 8: Introduction to F#

Interactive Scripting Good for prototyping

Succinct = Less code

Type Inference Strongly typed, strict

Automatic generalization (generics for free)

Few type annotations

1st class functions (currying, lazy evaluations)

Pattern matching

Key Characteristics of F#

Page 9: Introduction to F#

Multi-Paradigm Functional Programming

Imperative Programming

Object Oriented Programming

Language Oriented Programming

Task Oriented Programming

F# is not just Functional

Page 10: Introduction to F#

Dynamically compiles code on the fly

Example:

Demo

F# Interactive

open System.Drawing;; open System.Windows.Forms;;

let myform = new Form(Text="Hello Everybody", Visible=true);; myform.BackColor <- Color.Blue;; let mybutton = new Button(Text = "Click Me");;myform.Controls.Add(mybutton);; mybutton.BackColor <- Color.White;;

mybutton.Click.Add(fun _ -> MessageBox.Show("Clicked") |> ignore);;

Page 11: Introduction to F#

Type inference

Expressions

F# Basics

let x = 5let y = 5.0 let files = Directory.GetFiles(@"C:\images\original")

let x = 5 * 5let y = 5.0 / 3.0let width = image.Width / 8

Page 12: Introduction to F#

Function

Anonymous functions

F# Functions

let sqr x = x * xsqr 5

(fun x -> x * x) 5

Page 13: Introduction to F#

The |> Combinator “Pipe Forward”

Example

F# Combinators

x |> f is the same as f x

let sqr x = x * x sqr x 5 |> sqr

Page 14: Introduction to F#

Partial functions

Don’t have to pass all parameters at once

Curried Functions

let DivideBy y x = x / ylet result = DivideBy 2.0 3.0

val DivideBy : float -> float -> floatval result : float = 1.5

let HalfOf = DivideBy 2.0let result2 = HalfOf 3.0

val HalfOf : (float -> float)val result2 : float = 1.5

Page 15: Introduction to F#

Pass curried function to another function

Power of Curried Functions

let DivideBy y x = x / ylet numbers = [1.0; 2.0; 3.0]let result3 = List.map (DivideBy 2.0) numbers

val DivideBy : float -> float -> floatval numbers : float list = [1.0; 2.0; 3.0]val result3 : float list = [0.5; 1.0; 1.5]

Page 16: Introduction to F#

Compare with VBFunction DivideBy(ByVal y As Single, _

ByVal x As Single) As Single Return x / yEnd Function

Sub Main() Dim numbers = New Single() {1.0, 2.0, 3.0} Dim result3 As New List(Of Single)

For Each number In numbers result3.Add(DivideBy(2.0, number)) NextEnd Sub

Page 17: Introduction to F#

used to group values together without creating a class or struct

Tuple#lightopen System

let swap (x, y) = (y, x)let rotate (x, y, z) = (y, z, x)let circleDetails radius = let area = Math.PI * (radius * radius) let circumference = 2.0 * Math.PI * radius (area, circumference)

let result1 = swap(3, 2)let result2 = rotate(5, 6, 7)let details = circleDetails 4.0let (a, c) = details

Tuple as a

function

parameter

Tuple as a return value

Tuple as left

side of an

assignment

Page 18: Introduction to F#

Similar to Object Oriented inheritance

Useful in pattern matching

Discriminated Unions

type Suit = | Spades | Hearts | Clubs | Diamonds let suits = [Spades; Hearts; Clubs; Diamonds]

Page 19: Introduction to F#

Discriminated Unions cont.type Suit = | Spades | Hearts | Clubs | Diamonds

type Card = | Ace of Suit | RankCard of int * Suit | Jack of Suit | Queen of Suit | King of Suit | Joker

let card1 = Ace(Diamonds)let card2 = RankCard(3, Spades)let card3 = Joker

Page 20: Introduction to F#

Used often in F# programs

Syntax (source: http://en.wikibooks.org/wiki/F_Sharp_Programming/Pattern_Matching_Basics )

Pattern Matching

Page 21: Introduction to F#

Mouse event handler in DirectX Demo

Checking mouse button and shift key modifiers

Pattern Matching Example

match b.Button, Form.ModifierKeys with | MouseButtons.Left, Keys.Shift -> view.AdjustZoom(dx,dy) | MouseButtons.Left, _ -> view.AdjustYawPitchRoll(dx,dy) | _ -> view.AdjustFocus(dx,dy)

Page 22: Introduction to F#

FSharp Samples v0.2

The DirectX Demo

More F# Interactivehttp://code.msdn.microsoft.com/fsharpsamples

Page 23: Introduction to F#

The Power Wall

Manycore FUD

Free lunch is over

Parallel programming in .NET

Where F# fits into this future

F# and Impact on the Future

Page 24: Introduction to F#

The Power Wall: CPU Clock Speed

From Katherine Yelick’s “Multicore: Fallout of a Hardware Revolution”

Page 25: Introduction to F#

Fear, Uncertainty, and Doubt Talbott’s FUD slide: why you should be concerned

Moore’s Law Predicted in 1965 that transistor density in semiconductor chips would

double every 18 months

Clock speed on chips plateaued in 2005 at 3 GHz due to the “Power Wall”

Intel and AMD have now begun doubling cores every 18 months to keep up with Moore’s Law AMD Opteron Istanbul and Intel Xeon have 6 cores per socket used in

Servers

Dell Studio XPS (2009 price of $750) comes with Intel i7 with 4 cores with 2 way hyper-threading (8 virtual cores)

Intel Larrabee on the horizon with 32 cores with 4 way hyper-threading (128 virtual cores)

FUD

Page 26: Introduction to F#

Source: Wikipedia entry for Larrabee (GPU)

Intel Larrabee

Page 27: Introduction to F#

Free lunch is over Programs are not doubling in speed every couple

of years for free anymore

We need to start writing code to take advantage of many cores

Currently painful and problematic to take advantage of many cores because of shared memory, locking, and other imperative programming techniques

Problem

Page 28: Introduction to F#

Libraries and Framework Improvements TPL (Included in .NET 4.0)

PLINQ

Programming Approaches Functional programming

Immutable data No side effects

Task oriented programming

Solution

Page 29: Introduction to F#

Parallel Programming in the .NET Framework 4 Beta 2

Page 30: Introduction to F#

“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” F# FAQ: http://bit.ly/FSharpFAQ

Functional programming is a primary technique for minimizing/isolating mutable state

Asynchronous workflows make writing parallel programs in a “natural and compositional style”

F# and Multi-Core Programming

Page 31: Introduction to F#

Problem Resize a ton of images

Demo of Image Processor

for file in files do use image = Image.FromFile(file) use smallImage = ResizeImage(image) let destFileName = DestFileName("s1", file) smallImage.Save(destFileName)

let files = Directory.GetFiles(@"C:\images\original")

Page 32: Introduction to F#

Asynchronous Workflowslet FetchAsync(file:string) = async { use stream = File.OpenRead(file) let! bytes = stream.AsyncRead(int stream.Length) use memstream = new MemoryStream(bytes.Length) memstream.Write(bytes, 0, bytes.Length) use image = Image.FromStream(memstream) use smallImage = ResizeImage(image) let destFileName = DestFileName("s2", file) smallImage.Save(destFileName) }

let tasks = [for file in files -> FetchAsync(file)]let parallelTasks = Async.Parallel tasksAsync.RunSynchronously parallelTasks

Page 33: Introduction to F#

Almost 2x on 2 cores

About 3.5x faster on 8 cores

Demo Asynchronous Workflow

Page 34: Introduction to F#

F# User Group

http://fsug.org

Twitter: @FSUG

Talbott Crowell, ThirdM.com

http://talbottc.spaces.live.com

Twitter: @Talbott

Thank you for attending Intro to F#

Questions?