Functional Thinking is Fun and Powerful

Thinking with functions

defined by expressions

applied as transformations

to a sequence of data

= x - x^3/6
=xx3/6= x - x^3/6
f(x)
f(x)f(x)

To expand your mental weaponry in a way that can be applied outside purely functional languages

Purpose

Thinking with functions defined by expressions applied as transformations to a sequence of data

Pure Functions (a la Math)

function input = output
f(x) = ...x...
f(x)=...x...f(x) = ...x...

Thinking with functions defined by expressions applied as transformations to a sequence of data

Statements are executed

var trimmed = "";
if (toTrim != null)
{
    trimmed = toTrim.Trim();
}
return trimmed;
var x = 2;
return x;

Expressions are evaluated

2
22
3^2 + 4^2
32+423^2 + 4^2
\alpha\sin(\theta \div 2) + \beta
αsin(θ÷2)+β\alpha\sin(\theta \div 2) + \beta
if toTrim = null
then ""
else toTrim.Trim()
x
xx

Statement-based (C#)

class Cell {
    public bool IsAlive { get; set; }
    public Cell NextState(int livingNeighbors)
    {
	if ((IsAlive && livingNeighbors == 2) ||
            livingNeighbors == 3)
        {
            return new Cell { IsAlive = true };
        }
        return new Cell { IsAlive = false };
    }
}

Expression-based (F#)

type Cell = DeadCell | LivingCell

let nextStateOf cell livingNeighbors =
    match cell, livingNeighbors with
    | LivingCell, 2 -> LivingCell
    | _, 3 -> LivingCell
    | _ -> DeadCell

Expression-based C#

public Cell NextState(int livingNeighbors)
{
    return new Cell
    {
        IsAlive = (IsAlive && livingNeighbors == 2) ||
                  livingNeighbors == 3
    };
}

Thinking with functions defined by expressions applied as transformations to a sequence of data

Imperative (C#)

public bool ShouldOfferToGiftWrap()
{
    foreach (var item in Items)
    {
        if (item.IsFromWishlist)
        {
            return true;
        }
    }

    return false;
}

Functional (F#)

let shouldOfferToWrapGift order =
    List.exists (fun i -> i.IsFromWishlist) order.Items

Functional (C#)

public bool ShouldOfferToGiftWrapV2()
{
    // Yeah LINQ!
    return Items.Any(item => item.IsFromWishlist);
}

Functional (JavaScript)

var shouldOfferToGiftWrap = function(items) {
    return _(items).some(function(x) {
        return x.isFromWishlist;
    });
};

Map

Reduce

Could you simplify your code by thinking in terms of transformations on immutable data?

Could you simplify your code by recognizing known sequence operations and using LINQ or Underscore.js?

(But please, do not just click "Convert to LINQ"!)

Could you simplify your code by writing it in F# or Haskell?

Think

Functional Programming is Fun and Powerful

By Keith Pinson

Functional Programming is Fun and Powerful

Thinking with functions defined by expressions applied as transformations to a set of data

  • 1,075