Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Object-Oriented Programming in Functional Programming in Swift

2,212 views

Published on

Far from being mutually exclusive ways to write software, OOP and functional programming are two useful mental toolsets for designing software. Graham explores how the two are related to find out more about each.

Published in: Software
  • Be the first to comment

  • Be the first to like this

Object-Oriented Programming in Functional Programming in Swift

  1. 1. Object-Oriented Programming
  2. 2. …in Functional Programming Object-Oriented Programming
  3. 3. …in SwiftObject-Oriented Programming …in Functional Programming
  4. 4. –Randall Munroe “I’m being quoted to introduce something, but I have no idea what it is and certainly don’t endorse it.”
  5. 5. First, an assertion U A ⇔ f == ∀𝑥: 𝕌•𝑥∈A ⇔ isDuck(𝑥)
  6. 6. … ⇔ isDuck(𝑥)
  7. 7. Some sets let emptySet = {(_) in return false} let universe = {(_) in return true}
  8. 8. All sets typealias MySet<T> = (T) -> Bool
  9. 9. Parameterising sets func RangeSet(from lower: Int, to upper: Int) -> MySet<Int> { return { (x) in (x >= lower) && (x <= upper)} } func UnionSet<T>(of left: @escaping MySet<T>, and right: @escaping MySet<T>) -> MySet<T> { return { (x) in (left(x) || right(x))} }
  10. 10. Digression: 2 > 1 ⇔ Count: ℕ At: ℕ→T? <T> struct List<T> { let count: () -> Int let at: (Int) -> T? } protocol List { associatedtype T func count() -> Int func at(index: Int) -> T? } ⇔
  11. 11. struct List<T> { let count: () -> Int let at: (Int) -> T? } protocol List { associatedtype T func count() -> Int func at(index: Int) -> T? } ⇔ count f(𝑥) at g(𝑥)
  12. 12. count f() at g(𝑥)
  13. 13. enum ListSelectors { case count case at } enum ListIMPs<T> { case count (() -> Int) case at ((Int) -> T?) } typealias List<T> = (ListSelectors) -> ListIMPs<T>
  14. 14. If 2>1, then ∞>2 typealias Selector = String typealias Object = (Selector) -> IMP enum IMP { case accessor(()->(Object?) case mutator((Object)->Void) … } func swift_msgSend(this: Object, _cmd: Selector) -> IMP { return this(_cmd) }
  15. 15. TL;DR • Objects are functions • …that close over their ivars (constructors are HOFs) • …that map method selectors to method implementations • …they’re just ways to pick functions at runtime Sample code with more discussion: https://github.com/iamleeg/OOPInFPInSwift

×