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

Finding the Algebra in Algebraic Data Types

Finding the Algebra in Algebraic Data Types

Construction of an algebra using Swift's type system.

Johannes Weiss

October 19, 2015
Tweet

More Decks by Johannes Weiss

Other Decks in Technology

Transcript

  1. ALGEBRA? Algebra (from Arabic and Farsi "al-jabr" meaning "reunion of

    broken parts") is one of the broad parts of mathematics, together with number theory, geometry and analysis. In its most general form, algebra is the study of mathematical symbols and the rules for manipulating these symbols. — Wikipedia
  2. !

  3. DON'T WORRY ! One algebra you know from primary school

    > Symbols/Elements: !, ", #, $, ... > Manipulation/Operators: ➕➖✖➗
  4. () > () > Bool typealias One = () /*

    = Void */ typealias Two = Bool let theOne : [One] = [()] let allTwos : [Two] = [false, true]
  5. !" enum Zero { } let impossible : Zero =

    ! /* has no value */ let possibles : [Zero] = []
  6. ADDITION enum Add<L, R> { case AddL(L) case AddR(R) }

    typealias Three = Add<One, Two> /* Add<(), Bool> */ let allThrees : [Three] = [ .AddL(()), .AddR(false), .AddR(true)]
  7. typealias Five = Add<Three, Two> let fs : [Five] =

    [.AddL(.AddL(())), .AddL(.AddR(false)), .AddL(.AddR(true)), .AddR(false), .AddR(true)]
  8. MULTIPLICATION struct Mul<L, R> { let l : L let

    r : R } /* alternative: (L, R) */ typealias Four = Mul<Two, Two> let fours : [Four] = [Mul(l:false, r:false), Mul(l:false, r:true), Mul(l:true, r:false), Mul(l:true, r:true)]
  9. THE RULES typealias Two_ = Add<Two, Zero> let allTwo_s :

    [Two_] = [.AllL(false), .AddL(true)]
  10. typealias ThreeL = Add<One, Two> typealias ThreeR = Add<Two, One>

    let l : [ThreeL] = [.AddL(()), .AddR(false), .AddR(true)] let r : [ThreeR] = [.AddL(false), .AddL(true), .AddR(())]
  11. typealias Two__ = Mul<One, Two> let all2__ : [Two__] =

    [Mul(l:(), r:false), Mul(l:(), r:true)]
  12. FUNCTION TYPES enum Colour { case White; case Red }

    enum Fill { case None; case Pattern; case Solid } func myFavouriteFillForColour(colour : Colour) -> Fill { switch (colour) { case .White: return .Solid case .Red: return .Pattern } } How many functions myFavouriteFillForColour?
  13. > (A, B) -> C > (A) -> (B ->

    C) > currying ✅ func isNiceTuple(colour : Colour, fill : Fill) -> Bool { return true } func isNiceCurried(colour : Colour)(fill : Fill) -> Bool { return true }