Johannes Weiss
October 19, 2015
170

# Finding the Algebra in Algebraic Data Types

Construction of an algebra using Swift's type system.

October 19, 2015

## Transcript

2. ### 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

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

> Symbols/Elements: !, ", #, \$, ... > Manipulation/Operators: ➕➖✖➗

7. ### THE ALGEBRA OF SWIFT TYPES > Example elements: Int, Bool,

... > Example operator: Optional
8. ### COUNTING THE VALUES > Bool : [false, true] > UInt

: 0, 1, 2 ...

10. ### () > () > Bool typealias One = () /*

= Void */ typealias Two = Bool let theOne : [One] = [()] let allTwos : [Two] = [false, true]

13. ### !" enum Zero { } let impossible : Zero =

! /* has no value */ let possibles : [Zero] = []

17. ### 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)]

20. ### typealias Two__ = Mul<One, Two> let all2__ : [Two__] =

[Mul(l:(), r:false), Mul(l:(), r:true)]

C>>

24. ### 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?

26. ### FUNCTION TYPES > Colour , Fill > (Colour) -> Fill

turns out: > (A) -> B !

28. ### > (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 }