Break Free with Managed Functional Programming: An Introduction to F#

Preview:

DESCRIPTION

Originally developed by Microsoft Research, Cambridge, F# is an open-source, functional-first language in the ML family. Despite its lofty position as a first-class Visual Studio language for the past two releases and its cross-platform availability it hasn't seen widespread adoption in the business world. These slides take you on an introductory tour of F#, exploring how its constructs and terse syntax can allow you to write more stable, maintainable code while keeping you focused on the problem rather than the plumbing.

Citation preview

Break Free withManaged Functional

ProgrammingAn Introduction to F#

A language that doesn't affect the way you think about programming, is not worth knowing.

Alan Perlis, Epigrams on Programming, 1982

About Me• Dave Fancher• Blog: http://davefancher.com• Twitter: @davefancher• Email: dave@davefancher.com

My Background

Why F#?

LINQ: The Functional Gateway Drug• Learned about query syntax• The method syntax• Introduced me to functional principles

JavaScript, Too!• Functions are first class citizens• Its most powerful features are enabled by closures

Turning Functional• Began applying functional principles in my code• Immutability with readonly fields & properties• More delegation• Coding without side-effects

C# Was Getting Frustrating• Verbose and repetitive• Fragile• Ceremonial

An Accidental Discovery• Hanselminutes #311• F#

So, what is this F# thing?

F# is a succinct, expressive, and efficient functional and object-oriented language for Microsoft .NET that helps you write simple code to solve complex problems.

Origin• CLR Language• Microsoft Research, Cambridge

Lineage

ML OCaml F#

Multi-Paradigm• Imperative• Object-oriented• Functional

Licensing & Availability• First Class Citizen of Visual Studio since VS2010• Apache 2.0 License• Every major platform• Managed by F# Software Foundation

Ok, but why should I care?

Gaining Traction

Source: TIOBE Index, May 2014 (http://bit.ly/1cvhJp3)

F# Over Time

August 2011

March 2013

March 2014

Source: TIOBE Index, May 2014 (http://bit.ly/1nnmeWK)

Functional-First• Favors FP over other styles• Other styles are available if needed

Design Principles

Terse Syntax• Few keywords• Limited punctuation• Strong type inference• Implicit return values

Top-Down Evaluation• File order is significant• Declaration order is, too• Avoids inadvertent mutually recursive definitions• Inferred return values

Organization Constructs• Namespaces• Modules

Expression-Based• Everything returns a value• Eager evaluation

Immutable by Default• 3 Types of bindings• Immutable by default

Let Bindings

Mutability

Reference Cells

Using Function & Use Bindings

Type system

All CLR Types• Int32• String• Double• Float• DateTime• TimeSpan• Types from other assemblies• …

Enumerations

Functions• Every F# function accepts exactly one input and returns

exactly one output• No concept of void functions• No concept of parameterless functions

Unit• Denoted as ()• Indicates no specific value• Can safely be ignored• Usually indicative of a function that has some effect

Tuples

Tuples for out Parameters

Syntactic Tuples

Records

Discriminated Unions• Immutable• Structural Equality• Resemble enumerations but are more powerful• Versatile

DUs as Object Hierarchies

DUs as Trees

http://bit.ly/1g76AOv

Mitigating Null

Options

Integrated Units of Measure

Measure Types

Live Demo: Enforcing Units of Measure

Collection Types• Sequences – seq { … }• Arrays – [| … |]• Lists – [ … ]• Maps• Sets

Collection Modules• Provide functions for manipulating collections• Many LINQ-like operations

• map -> Select• reduce -> Aggregate• filter -> Where

F# Lists• Not List<‘T>• Immutable• [ … ]• List module• Cons operator ::• Concatenation operator @

Composing F# Lists With :: and @

Object-Oriented

Classes

Filthy little hobbitses. They stole it from us!

Classes

Interfaces

Implementing Interfaces

Inheritance & Virtual Members

Object Expressions

Functional λ

Functional programming is programming without assignment statements.

 Bob Martin, FP Basics, Episode 1 (http://bit.ly/1nnhDnm)

Functional Purity• F# is impure• Mutability and side-effects are

allowed

Functions as Data• Higher-order functions• Let-bound functions• Lambda expressions

Currying• Named for Haskell Curry• Arguments are applied individually• Changes function organization

Curried Addition & Expanded Form

Partial Application

Pipelining

Function Composition

Recursion• Preferred looping mechanism• Compiler optimizes for tail calls

Pattern Matching

Basic Pattern Matching

Built-in patterns• Null• Variable & Wildcard• Literal• Tuple• Record• Identifier

• Array• List• Cons• As• And• Or

Decomposing Tuples

Decomposing DUs

Active Patterns• Custom patterns• Special type of function called an Active Recognizer• Curried• Maximum number of cases is 7• Each input must map to a named case

Partial Active Patterns• Single custom case• Not restricted to 7 active patterns• Return value is option

Live Demo: Partial Active Patterns

Data Access

Language Features• Query Expressions• Type Providers

Live Demo: Using the OData Type Provider

Async & Parallel Programming

Asynchronous Workflows• Conceptually similar to async/await in C#• Works using lightweight callbacks and continuations

Agent-based programming• Borrowed from Erlang• In-memory queuing mechanism• Uses MailboxProcessor<‘T> for message passing• Implementation often includes asynchronous workflows

for monitoring

Live Demo: Agent-based Calculator

Computation Expressions

Extending the Language• Basis for several language features• Based on a builder class• Builder class methods map to familiar language

elements

Live Demo: Custom Computation Expression

In Summary• F# is a powerful, multi-paradigm language• Plays nicely with other CLR languages• Offers numerous constructs to keep you focused on the

problem rather than the plumbing• Simple code for complex problems

No matter what language you work in, programming in a functional style provides benefits. You should do it whenever it is convenient, and you should think hard about the decision when it isn’t convenient.

 John Carmack, Functional Programming in C++

The More You Know

• The Book of F#http://bit.ly/1hzHV6v

• F# Software Foundationhttp://fsharp.org

• Try F#http://tryfsharp.org

• F# Language Referencehttp://bit.ly/1koEoqK

Recommended