Skip to content

CodeMash: Curry Favor with Closures: An Introduction to Functional Programming

Presented by: Bill Wagner

These are “live” notes and necessarily rough.

Google for PLINQ, for an interview.

Closure: a combination of a function and its executing environment (not precise definition) Yield Return: syntactic sugar for iterator pattern.

Real World Use of Functional Programming

  • enumeration of the input
  • operation on that input
  • the output
  • could be sequence or scalar
  • payoff: enumeration, output are generic
  • payoff 2: operation can be anonymous
  • Framework 2.0 Examples

    • RemoveAll: call this method on every item in list, if returns true, remove item
    • Exists
    • Find, FindAll, FindLast, FindLastIndex
    • ForEach
    • TrueForAll

    We are always writing looping or branching constructs. Enumerate sequence is common. Scalar result from a sequence is common. Thread safety and closures. Since this pattern is so common, language changes can make this easier - hence C# 3.0.

    C# avoids problems with language change by using contextual keywords like “yield return” which onlly means something in special places. You should be able to take C# 2.0 and compile into C# 3.0.

    Why Add Functional Concepts

    • Programs = mathematical functions
    • e.g. y = f(x)
    • no side effects, no state, mapping between input and output
    • can prove that the function works, mathematically
  • they may be functions of functions:
    • z = f(g(x), y)
    • This is currying
    • There are MIT videos on functional programming
  • There are no side effects
    • Functions have inputs, and one output
    • They don’t change other values (no state changes)
    • member variables, or global variables

    Extension Methods

    • injected into existing class
    • extension methods are last in method resolution order
    • String has a concat(), so the extension method won’t execute
  • ToArray(), ToList() are important to know (System.Linq)
    • immediate vs. deferred execution
  • Can even add methods onto a sealed class
  • Lambdas

    • Lambdas are shorthand for anonymous delegates. You write this:
    • x => x + 1
  • Compiler creates full delegate code
  • ‘var’ is not weak typing, or dynamic typing
    • is local type inference
    • sometimes called ‘Duck Typing
  • Compiler infers type of variable from right-hand-side of experssion
  • only local to a procedure
  • can’t change type after init
  • If you want to try, need to search and find dll. Namespace is System.Linq.

    There was lots of good stuff in this presentation. These notes are very incomplete. I’ll link to the slides, if they become available online.

    Fin.

    Post a Comment

    Your email is never published nor shared. Required fields are marked *