Get Functional on the CLR: Intro to Functional Programming with F#

Post on 08-May-2015

396 views 2 download

description

As presented at Prairie Dev Con 2014 in Winnipeg, Manitoba on Monday, April 7, 2014

Transcript of Get Functional on the CLR: Intro to Functional Programming with F#

Get Functional on the CLR: Intro to Functional Programming with

F#

David Alpert | @davidalpert | http://about.me/davidalpert

Learning Goals

• Disambiguate functional programming

• Demystify F# and F# syntax

• Demonstrate .NET interoperability

• Experiment with F# syntax

• Create a new F# library project

• Write basic functions and data structures in F#

• Call F# from C#

So that you will be able to:

Put yourself in “I have no idea what I’m doing” situations more

often. Your growth will be exponential. - @derekbailey

htt

ps:

//tw

itte

r.co

m/d

eric

kbai

ley/

stat

us/

45

28

32

02

28

60

29

20

96

Woody Zuill

“Question Everything – put special focus on our deepest held beliefs. What we trust most hides our biggest problems.”

Agile Maxim #2

http://zuill.us/WoodyZuill/2012/09/16/the-8-agile-maxims-of-woody-zuill/

We are addicted to complexity

We are addicted to complexity

We are addicted to accidental complexity

We are addicted to accidental complexity

We are addicted to manipulating state

We are addicted to manipulating state

#noManipulatingState is like #noDefects or #NoEstimates #noManipulatingState

is like #noDefects

or #noEstimates

What is Functional Programming?

It is programming... with functions!

• Pure – Referentially Transparent

• First Class and Higher-Order functions

• Partial application & Currying

What is Functional Programming?

(function ($) { $(document).ready(function () { $('dt').click(function (ev) { // do something interesting }); function doSomethingElse(ev) { // something else again } $('a').click(doSomethingElse); }); })(jQuery);

Func<int, bool> isEven = x => x%2 == 0; public static MvcHtmlString LabelFor<TModel, TValue>( this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) { // ... } var someString = @Html.TextBoxFor(model => model.Rating)

Why F#?

• Concise

• Convenient

• Correctness

• Concurrency

• Complete

Concise

Convenient

Correctness

Concurrency

Complete

The “Billion Dollar Mistake”

http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare

Sir Charles Antony Richard Hoare, commonly known as Tony Hoare, is a British computer scientist, probably best known for the development in 1960, at age 26, of Quicksort. He also developed Hoare logic, the formal language Communicating Sequential Processes (CSP), and inspired the Occam programming language. Tony Hoare introduced Null references in ALGOL W back in 1965 “simply because it was so easy to implement”, says Mr. Hoare. He talks about that decision considering it “my billion-dollar mistake”.

We are addicted to accidental complexity

We are addicted to accidental complexity

From C# syntax to F# syntax C# F#

Curly braces denote scope Indentation (i.e. Whitespace) denotes scope

Brackets and commas in argument list No brackets or commas

// single line comment // single line comment

/* multi-line comment */ (* multi-line comment *)

Explicit return Implicit return (value of the last expression)

public int Add(int x, int y) { return x + y; }

let add x y = x + y

IEnumerable<T> seq<‘T>

IList<T> ‘T list

Null None ( an Option value)

Some more F# syntax Description Syntax Evaluates to

Declare a list (of int) [2; 3; 4] int list = [2; 3; 4]

Prepend to a list 1 :: [2; 3; 4] int list = [1; 2; 3; 4]

Contact two lists [0; 1] @ [2; 3; 4] int list = [0; 1; 2; 3; 4]

Declare a tuple of int (1, 2, 3) int * int * int = (1, 2, 3)

Declare an optional value let x = Some(1) val x : int option = Some 1

Declare a ‘null’ value Let z = None val z : 'a option

Pipe a list into a function (like Linq’s Select)

[1; 2; 3] |> (fun x -> x ^ 2)

int list = [1; 4; 9]

Functional Type Notation

let add1 x = x + 1 int -> int

let add x y = x + y int -> int -> int

Basic List Functions

List.filter : ('T -> bool) -> 'T list -> 'T list List.map : ('T -> 'U) -> 'T list -> 'U list List.fold : ('State -> 'T -> 'State) -> 'State -> 'T list -> 'State

predicate items result

projection items result

accumulator items final state

initial state

+ new item = final state

initial state

Basic List Functions

predicate items result

projection items result

items

final state initial

state accumulator

+ new item = final state

initial state

public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate )

public static IEnumerable<TResult> Select<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, TResult> selector )

public static TAccumulate Aggregate<TSource, TAccumulate>( this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func )

Demo: Rapid Prototyping with FSI

• Rapid prototyping with the FSI REPL and the F# Interactive Window Demo:

Rapid Prototyping w/ FSI REPL & the F# Interactive window

Demo: File -> New F# Project

• Create a new F# library project

• Create a new C# library project w/ Nunit

• Add references and test F# code from C# Demo: File -> New F# Project

Demo: Other goodies

• Parsing with FParsec (a parser-combinator approach)

• Strongly-typed Units of Measure

• Domain Modelling (i.e. Lightweight DDD)

• Automated browser testing with Canopy

Demo: Other F# goodies

References & Resources Get Functional on the CLR:

Intro to Functional Programming with F#

David Alpert | @davidalpert | http://about.me/davidalpert

Reference

• http://en.wikipedia.org/wiki/Functional_programming

• http://fsharpforfunandprofit.com/why-use-fsharp/

• http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare

• http://www.tryfsharp.org/Create

• http://fsharpforfunandprofit.com/posts/fsharp-in-60-seconds/

• http://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/

• http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/fsharp-component-design-guidelines.pdf [ Component design guidelines ]

• http://visualstudiogallery.msdn.microsoft.com/07636c36-52be-4dce-9f2e-3c56b8329e33 [ depth colorizer ]

Examples

• http://www.quanttec.com/fparsec/ [ A parser-combinator library ]

• https://github.com/davidalpert/furlstrong [ F# based url parsing with FParsec ]

• http://nuggle.me/ [ DC Circuits in F# ]

• http://blogs.msdn.com/b/andrewkennedy/archive/2008/08/29/units-of-measure-in-f-part-one-introducing-units.aspx [ Custom units of measure in F# ]

• http://www.slideshare.net/ScottWlaschin/ddd-with-fsharptypesystemlondonndc2013 [ DDD & F# Types ]

• http://lefthandedgoat.github.io/canopy/ [ Browser automation DSL with F# ]