• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Break Free with Managed Functional Programming: An Introduction to F#
 

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

on

  • 691 views

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 ...

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.

Statistics

Views

Total Views
691
Views on SlideShare
341
Embed Views
350

Actions

Likes
0
Downloads
8
Comments
0

6 Embeds 350

http://davefancher.com 341
http://www.newsblur.com 4
https://www.newsblur.com 2
http://www.slideee.com 1
http://davefancher.wordpress.com 1
http://prlog.ru 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Developing software for > 10 years <br /> Mostly C#/.NET <br /> Before that, some Visual Basic, and classic ASP <br /> But most important for tonight…
  • People often ask: Why F#? Why not Haskell, Scala, or Erlang? <br /> Question presupposes intent; I didn’t set out to learn a functional language. <br /> I outgrew C# and F# matched the way I think..
  • Query Syntax: <br /> Syntactic sugar <br /> Compiles to method syntax <br /> Added after early adopters reported being confused <br /> <br /> Method Syntax: <br /> Matched the way I think <br /> <br /> Functional Principles: <br /> Purity <br /> Referential transparency <br /> Higher-order functions <br />
  • If you’re treating JS as an OO language, you’re doing it wrong <br /> JS objects are glorified dictionaries (hashes)
  • Verbose <br /> Generic delegates are verbose & hard to read <br /> <br /> Repetition: <br /> How many times does the compiler need to be told what type something is? <br /> <br /> Fragile: <br /> Reference types can change at any time <br /> Side-effects are common <br /> <br /> Ceremony: <br /> Curly braces <br /> Parenthesis <br /> Explicit returns <br /> (training wheels)
  • Mowing the lawn <br /> Hanselminutes #311 <br /> Philip Trelford & Richard Minerich <br /> F#, a functional language for the CLR
  • Statement doesn’t tell the whole story
  • CLR Language: <br /> First-class citizen of VS since 2010 <br /> Compiles to CIL <br /> Strongly-typed <br /> Offers cross-language compatibility <br /> Realizing the early promise of .NET <br /> Often used in mixed language solutions <br /> Don Syme – helped develop .NET generics
  • The live demos are Windows-centric but you can use other platforms <br /> Apache 2.0 <br /> F# Software Foundation <br /> Every major platform <br />
  • Climbed 25 spots since May 2013
  • Fizzled out around June 2012 then began its ascent in March 2013
  • Often lead to better code <br /> Often results in less code <br /> Generally easier to reason about code <br /> Let you stay focused on the problem <br /> Enforces many Clean Code guidelines <br /> Evolution of SOLID (ref: Mark Seeman’s blog @ ploeh.dk)
  • Like CShell <br /> More interactive than LINQPad
  • Note: No NuGet Support <br /> <br /> Example: <br /> let add x y = x + y <br /> add 5 10;; <br />
  • Terse Syntax <br /> Top-down <br /> Constructs <br /> Expression-based <br />
  • Namespaces <br /> Same as other languages <br /> Logical grouping of code to avoid naming conflicts <br /> <br /> Modules <br /> Static classes <br /> Contain only values or functions <br /> Let-bound functions cannot be overloaded <br /> Can be opened (imported) like namespaces <br /> AutoOpenAttribute makes module members visible by opening the module with the namespace is opened <br />
  • Don’t work with closures <br /> C#’s variables work only through compiler magic
  • Alternative to mutable let bindings <br /> Concrete type wraps a mutable value <br /> Necessary for mutating within closures (C# does some compiler tricks to hide this) <br /> Also allow passing values by reference
  • Using function returns a value! <br />
  • Reduces complexity since there’s only one type of function rather than 9 generic overloads of Func and Action <br />
  • Same underlying types as in C# <br /> Tuple, and remaining incompatible overloads <br /> Easier <br /> Native syntax – if you see a comma, it’s a tuple <br />
  • Light-weight classes <br /> Immutable by default <br /> CLIMutable for standard .NET serialization <br /> Structural equality <br /> Visual Studio Demo
  • Immutable dictionary <br /> Good for unchanging data <br /> No syntactic shortcuts <br /> Map module <br />
  • Looping <br /> while loops <br /> Simple For loops <br /> Enumerable For loops <br /> <br /> Branching <br /> if expressions <br /> if..elif expressions <br /> These are expressions <br /> if must yield unit <br /> if..elif blocks must return both the same type <br />
  • Overlooked: <br /> Sometimes necessary for language interop <br /> Sometimes it’s the right tool for the job <br /> <br /> Power: <br /> Can create rich models with classes, structs, and interfaces <br /> Polymorphism, inheritance, and encapsulation <br /> No concept of protected in F# code but protected members from other languages are still honored <br /> <br /> Object Expressions: <br /> Inline type definitions
  • Ask about C# 6 features <br /> Primary constructors <br /> Auto-properties with initializers
  • Concrete <br /> Abstract <br /> No static classes <br /> static members are allowed <br /> use modules or simulate by making members static and sealing <br /> Constructors <br /> Primary constructors simplify instantiation (C# stole it from us <br /> Additional constructors allow chaining <br /> No auto-generated default constructor <br /> Implicit field definitions <br /> Primary constructor parameters become private fields
  • Virtual members in F# more closely represent how they’re implemented in the CLR. Abstract defines the slot in the virtual method lookup table and default provides the implementation.
  • Think of as lambda expressions for types <br /> Inline implementations of interfaces or base classes <br /> Useful as fake objects in unit testing or other places where formal types are overkill <br />
  • Purity: <br /> F# is impure <br /> Mutability is allowed <br /> Functions can have side-effects <br /> Care should be taken to isolate side-effects
  • Enabled by currying <br /> Applying the first n arguments results in a new function <br /> Used frequently in pipelined operations <br />
  • Lets data flow through operations <br /> Reverses the argument and function <br /> Single-use <br />
  • Like pipelining but creates a new function <br /> Reusable <br />
  • Each of these are the basis for bindings; bindings use these
  • Discuss function syntax
  • Query Expressions <br /> LINQ for F# <br /> Nullable operators <br /> Type Providers <br /> Built-in Providers <br /> SQL Server <br /> Entity Framework <br /> OData <br /> WSDL <br /> Some Third Party Providers <br /> App Settings <br /> Excel <br /> File System <br /> Regex <br /> XAML <br /> <br /> <br />

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

  • Break Free with Managed Functional Programming An 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 Foundation http://fsharp.org • Try F# http://tryfsharp.org • F# Language Reference http://bit.ly/1koEoqK