Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Functional Programming Patterns

Robin Palotai
September 18, 2012

Functional Programming Patterns

A short enumeration of selected patters occuring in FP.

Robin Palotai

September 18, 2012
Tweet

More Decks by Robin Palotai

Other Decks in Programming

Transcript

  1. 1st class functions Functions are values too. They have type.

    Can be assigned to variables. f: a b → g: (a, b) c → input type output type → multiple arguments
  2. Higher order funs A higher order function is a function

    that takes other functions as argument. h: ([a], a b) [b] → → list elem mapper Strategy pattern-like
  3. Currying f: (a, b) c → f: a b c

    → → f: a (b c) → → curried form right-associative Factory pattern-like
  4. Pure Functions Referential transparency – expression replaceable with its value

    without changing program semantics. easy to reason about optimizable
  5. tuples and Lists pair: (a, b) 3-tuple: (a, b, c)

    1 :: 2 :: 3 :: Nil [1, [2, [3, []]]] heterogeneous fixed lengthc homogeneous unbounded length
  6. Algebraic Data Types data List a = Cons a (List

    a) | Nil data Tree a = Node (Tree a) a (Tree a) | Empty
  7. Functor A functor is a computational context. Map applies a

    normal function to a value in a context. map: f a (a b) f b → → → F<A> (A B) F<B> → → → fmap
  8. Monad point: a f a → flatMap: f a (a

    f b) f → → → b A context with richer operations. pure, return bind
  9. Option Nulls made explicit. No more NPE. data Option a

    = Some a | None orElse: Opt a Opt a Opt a → → getOrElse: Opt a a a → → Monad
  10. Either data Either a b = Left a | Right

    b Often used for error handling, where error is on the left, success on the right. Monad for a fixed a
  11. Future Promise / Future is a context, where the contained

    computation may execute concurrently. Used to compose async computations without blocking. Monad
  12. Typeclasses A typeclass describes a contract. A typeclass instance describes

    how a given data type fulfills that contract. Like an Adapter, but more versatile.
  13. Semigroup Monoid , Semigroup defines addition. Monoid is semigroup with

    an identity element. Pops all over your code!
  14. Foldable A foldable provides means for stateful traversal. foldLeft: f

    a b (b a b) b → → → → → Nice cooperation with Monoids
  15. Thx