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

  • 854 views
Uploaded on

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.

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
854
On Slideshare
0
From Embeds
0
Number of Embeds
5

Actions

Shares
Downloads
9
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • Developing software for > 10 years
    Mostly C#/.NET
    Before that, some Visual Basic, and classic ASP
    But most important for tonight…
  • People often ask: Why F#? Why not Haskell, Scala, or Erlang?
    Question presupposes intent; I didn’t set out to learn a functional language.
    I outgrew C# and F# matched the way I think..
  • Query Syntax:
    Syntactic sugar
    Compiles to method syntax
    Added after early adopters reported being confused

    Method Syntax:
    Matched the way I think

    Functional Principles:
    Purity
    Referential transparency
    Higher-order functions
  • If you’re treating JS as an OO language, you’re doing it wrong
    JS objects are glorified dictionaries (hashes)
  • Verbose
    Generic delegates are verbose & hard to read

    Repetition:
    How many times does the compiler need to be told what type something is?

    Fragile:
    Reference types can change at any time
    Side-effects are common

    Ceremony:
    Curly braces
    Parenthesis
    Explicit returns
    (training wheels)
  • Mowing the lawn
    Hanselminutes #311
    Philip Trelford & Richard Minerich
    F#, a functional language for the CLR
  • Statement doesn’t tell the whole story
  • CLR Language:
    First-class citizen of VS since 2010
    Compiles to CIL
    Strongly-typed
    Offers cross-language compatibility
    Realizing the early promise of .NET
    Often used in mixed language solutions
    Don Syme – helped develop .NET generics
  • The live demos are Windows-centric but you can use other platforms
    Apache 2.0
    F# Software Foundation
    Every major platform
  • Climbed 25 spots since May 2013
  • Fizzled out around June 2012 then began its ascent in March 2013
  • Often lead to better code
    Often results in less code
    Generally easier to reason about code
    Let you stay focused on the problem
    Enforces many Clean Code guidelines
    Evolution of SOLID (ref: Mark Seeman’s blog @ ploeh.dk)
  • Like CShell
    More interactive than LINQPad
  • Note: No NuGet Support

    Example:
    let add x y = x + y
    add 5 10;;
  • Terse Syntax
    Top-down
    Constructs
    Expression-based
  • Namespaces
    Same as other languages
    Logical grouping of code to avoid naming conflicts

    Modules
    Static classes
    Contain only values or functions
    Let-bound functions cannot be overloaded
    Can be opened (imported) like namespaces
    AutoOpenAttribute makes module members visible by opening the module with the namespace is opened
  • Don’t work with closures
    C#’s variables work only through compiler magic
  • Alternative to mutable let bindings
    Concrete type wraps a mutable value
    Necessary for mutating within closures (C# does some compiler tricks to hide this)
    Also allow passing values by reference
  • Using function returns a value!
  • Reduces complexity since there’s only one type of function rather than 9 generic overloads of Func and Action
  • Same underlying types as in C#
    Tuple<‘T>, and remaining incompatible overloads
    Easier
    Native syntax – if you see a comma, it’s a tuple
  • Light-weight classes
    Immutable by default
    CLIMutable for standard .NET serialization
    Structural equality
    Visual Studio Demo
  • Immutable dictionary
    Good for unchanging data
    No syntactic shortcuts
    Map module
  • Looping
    while loops
    Simple For loops
    Enumerable For loops

    Branching
    if expressions
    if..elif expressions
    These are expressions
    if must yield unit
    if..elif blocks must return both the same type
  • Overlooked:
    Sometimes necessary for language interop
    Sometimes it’s the right tool for the job

    Power:
    Can create rich models with classes, structs, and interfaces
    Polymorphism, inheritance, and encapsulation
    No concept of protected in F# code but protected members from other languages are still honored

    Object Expressions:
    Inline type definitions
  • Ask about C# 6 features
    Primary constructors
    Auto-properties with initializers
  • Concrete
    Abstract
    No static classes
    static members are allowed
    use modules or simulate by making members static and sealing
    Constructors
    Primary constructors simplify instantiation (C# stole it from us
    Additional constructors allow chaining
    No auto-generated default constructor
    Implicit field definitions
    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
    Inline implementations of interfaces or base classes
    Useful as fake objects in unit testing or other places where formal types are overkill
  • Purity:
    F# is impure
    Mutability is allowed
    Functions can have side-effects
    Care should be taken to isolate side-effects
  • Enabled by currying
    Applying the first n arguments results in a new function
    Used frequently in pipelined operations
  • Lets data flow through operations
    Reverses the argument and function
    Single-use
  • Like pipelining but creates a new function
    Reusable
  • Each of these are the basis for bindings; bindings use these
  • Discuss function syntax
  • Query Expressions
    LINQ for F#
    Nullable operators
    Type Providers
    Built-in Providers
    SQL Server
    Entity Framework
    OData
    WSDL
    Some Third Party Providers
    App Settings
    Excel
    File System
    Regex
    XAML


Transcript

  • 1. Break Free with Managed Functional Programming An Introduction to F#
  • 2. A language that doesn't affect the way you think about programming, is not worth knowing. Alan Perlis, Epigrams on Programming, 1982
  • 3. About Me • Dave Fancher • Blog: http://davefancher.com • Twitter: @davefancher • Email: dave@davefancher.com
  • 4. My Background
  • 5. Why F#?
  • 6. LINQ: The Functional Gateway Drug • Learned about query syntax • The method syntax • Introduced me to functional principles
  • 7. JavaScript, Too! • Functions are first class citizens • Its most powerful features are enabled by closures
  • 8. Turning Functional • Began applying functional principles in my code • Immutability with readonly fields & properties • More delegation • Coding without side-effects
  • 9. C# Was Getting Frustrating • Verbose and repetitive • Fragile • Ceremonial
  • 10. An Accidental Discovery • Hanselminutes #311 • F#
  • 11. So, what is this F# thing?
  • 12. 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.
  • 13. Origin • CLR Language • Microsoft Research, Cambridge
  • 14. Lineage ML OCaml F#
  • 15. Multi-Paradigm • Imperative • Object-oriented • Functional
  • 16. Licensing & Availability • First Class Citizen of Visual Studio since VS2010 • Apache 2.0 License • Every major platform • Managed by F# Software Foundation
  • 17. Ok, but why should I care?
  • 18. Gaining Traction Source: TIOBE Index, May 2014 (http://bit.ly/1cvhJp3)
  • 19. F# Over Time August 2011 March 2013 March 2014 Source: TIOBE Index, May 2014 (http://bit.ly/1nnmeWK)
  • 20. Functional-First • Favors FP over other styles • Other styles are available if needed
  • 21. Design Principles
  • 22. Terse Syntax • Few keywords • Limited punctuation • Strong type inference • Implicit return values
  • 23. Top-Down Evaluation • File order is significant • Declaration order is, too • Avoids inadvertent mutually recursive definitions • Inferred return values
  • 24. Organization Constructs • Namespaces • Modules
  • 25. Expression-Based • Everything returns a value • Eager evaluation
  • 26. Immutable by Default • 3 Types of bindings • Immutable by default
  • 27. Let Bindings
  • 28. Mutability
  • 29. Reference Cells
  • 30. Using Function & Use Bindings
  • 31. Type system
  • 32. All CLR Types • Int32 • String • Double • Float • DateTime • TimeSpan • Types from other assemblies • …
  • 33. Enumerations
  • 34. Functions • Every F# function accepts exactly one input and returns exactly one output • No concept of void functions • No concept of parameterless functions
  • 35. Unit • Denoted as () • Indicates no specific value • Can safely be ignored • Usually indicative of a function that has some effect
  • 36. Tuples
  • 37. Tuples for out Parameters
  • 38. Syntactic Tuples
  • 39. Records
  • 40. Discriminated Unions • Immutable • Structural Equality • Resemble enumerations but are more powerful • Versatile
  • 41. DUs as Object Hierarchies
  • 42. DUs as Trees
  • 43. http://bit.ly/1g76AOv Mitigating Null
  • 44. Options
  • 45. Integrated Units of Measure
  • 46. Measure Types
  • 47. Live Demo: Enforcing Units of Measure
  • 48. Collection Types • Sequences – seq { … } • Arrays – [| … |] • Lists – [ … ] • Maps • Sets
  • 49. Collection Modules • Provide functions for manipulating collections • Many LINQ-like operations • map -> Select • reduce -> Aggregate • filter -> Where
  • 50. F# Lists • Not List<‘T> • Immutable • [ … ] • List module • Cons operator :: • Concatenation operator @
  • 51. Composing F# Lists With :: and @
  • 52. Object-Oriented
  • 53. Classes
  • 54. Filthy little hobbitses. They stole it from us!
  • 55. Classes
  • 56. Interfaces
  • 57. Implementing Interfaces
  • 58. Inheritance & Virtual Members
  • 59. Object Expressions
  • 60. Functional
  • 61. Functional programming is programming without assignment statements. Bob Martin, FP Basics, Episode 1 (http://bit.ly/1nnhDnm)
  • 62. Functional Purity • F# is impure • Mutability and side-effects are allowed
  • 63. Functions as Data • Higher-order functions • Let-bound functions • Lambda expressions
  • 64. Currying • Named for Haskell Curry • Arguments are applied individually • Changes function organization
  • 65. Curried Addition & Expanded Form
  • 66. Partial Application
  • 67. Pipelining
  • 68. Function Composition
  • 69. Recursion • Preferred looping mechanism • Compiler optimizes for tail calls
  • 70. Pattern Matching
  • 71. Basic Pattern Matching
  • 72. Built-in patterns • Null • Variable & Wildcard • Literal • Tuple • Record • Identifier • Array • List • Cons • As • And • Or
  • 73. Decomposing Tuples
  • 74. Decomposing DUs
  • 75. 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
  • 76. Partial Active Patterns • Single custom case • Not restricted to 7 active patterns • Return value is option
  • 77. Live Demo: Partial Active Patterns
  • 78. Data Access
  • 79. Language Features • Query Expressions • Type Providers
  • 80. Live Demo: Using the OData Type Provider
  • 81. Async & Parallel Programming
  • 82. Asynchronous Workflows • Conceptually similar to async/await in C# • Works using lightweight callbacks and continuations
  • 83. Agent-based programming • Borrowed from Erlang • In-memory queuing mechanism • Uses MailboxProcessor<‘T> for message passing • Implementation often includes asynchronous workflows for monitoring
  • 84. Live Demo: Agent-based Calculator
  • 85. Computation Expressions
  • 86. Extending the Language • Basis for several language features • Based on a builder class • Builder class methods map to familiar language elements
  • 87. Live Demo: Custom Computation Expression
  • 88. 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
  • 89. 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++
  • 90. 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