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

Going Swiftly to a Functional World

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest. →

Going Swiftly to a Functional World

Original talk by Ana María Márquez and Javier de Silóniz, presented at NSSpain on September 2015. We introduce "Second Bridge", a Swift framework that includes several features from the Scala language to iOS/OSX platforms; and also introduce the very basic foundations of Functional Programming.

Avatar for Javier de Silóniz Sandino

Javier de Silóniz Sandino

September 16, 2015

More Decks by Javier de Silóniz Sandino

Other Decks in Programming

Transcript

  1. GOING SWIFTLY TO A FUNCTIONAL WORLD 47deg.com 1 Ana Márquez

    Javier de Silóniz @anamariamarvel @JaviTaiyou
  2. ABOUT 47 DEGREES 47deg.com 2 47 Degrees is a global

    consulting firm with offices in Seattle (Washington) and San Fernando (Cádiz). Our team works in several fields of expertise, comprising software as diverse as iOS apps or Scala-powered Big Data backends. We’re really serious about the quality of our code and work, but we also love to have fun!
  3. GOING SWIFTLY TO A FUNCTIONAL WORLD 47deg.com 3 We’d like

    to introduce you to Second Bridge: a Swift framework that introduces several new functional concepts with a Scala-like syntax, and new data types coming from the Scala/Haskell world that can make your programming process cleaner and easier.
  4. FUNCTIONAL PROGRAMMING LANGUAGES 47deg.com 4 Clean Elm Coq (Gallina) Charity

    Frege SequenceL Idris Miranda Haskell Curry (Pure) Hope
  5. FUNCTIONAL PROGRAMMING LANGUAGES 47deg.com 5 Clean Elm Coq (Gallina) Charity

    Frege SequenceL Idris Miranda Haskell Curry (Pure and impure) Hope C++ 1 1 C# D Erlang F# Java 8 Javascript Joy Julia Lisp Clojure Emacs Lisp Scheme Mathematica OCaml Python Ruby Rust Scala Common Lisp ML
  6. FUNCTIONAL PROGRAMMING LANGUAGES 47deg.com 5 Clean Elm Coq (Gallina) Charity

    Frege SequenceL Idris Miranda Haskell Curry (Pure and impure) Hope C++ 1 1 C# D Erlang F# Java 8 Javascript Joy Julia Lisp Clojure Emacs Lisp Scheme Mathematica ML OCaml Python Ruby Rust Scala Common Lisp Swift?
  7. BENEFITS OF FUNCTIONAL PROGRAMMING 47deg.com 7 Although FP has been

    adopted more in academia rather than in industry for decades, this trend is changing in recent years for several reasons: • Code can be cleaner, more reusable and extremely testable • Functional code works really well in multi- core systems (the norm nowadays in desktop, server and mobile environments)
  8. BASIC ELEMENTS OF FP 47deg.com 8 •First class functions •Higher-order

    functions •Pure functions •Recursion •Immutability •Avoiding state and side-effects
  9. FIRST-CLASS FUNCTIONS 47deg.com 10 func printResults(f:()->String) -> String { return

    f() } func sayHello() -> String { return "Hello World" } printResults(sayHello) // “Hello World” func createMultiplier(factor:Int) -> (Int) -> Int { return {(n:Int)-> Int in return n*factor } } let twice = createMultiplier(2) twice(2) // 4 Functions can take other functions as parameters Functions can return other functions
  10. HIGHER-ORDER FUNCTIONS 47deg.com 1 1 Functions that return other functions,

    or functions that take a function as an argument, returning the result of applying it to its other arguments. There are several standard frequently-used HOF in FP, like fold, flatMap, filter, map, reduce… let evenSum = Array(1...10) .filter { (number) in number % 2 == 0 } .reduce(0) { (total, number) in total + number }
  11. PURE FUNCTIONS 47deg.com 13 var counter = 0 func incCounter(factor:

    Int) { for i in 0..<factor { counter++ } } incCounter(20) Functions that depend on state are complex to test (i.e: here we’d need to mock the counter) func countBy(factor: Int, counter: Int) -> Int { if factor == 0 { return counter } return countBy(factor - 1, counter + 1) } This function here doesn’t depend on any external variable, and it’s easier to test and therefore to maintain.
  12. RECURSION 47deg.com 14 In pure FP, recursion is the basic

    foundation of loops (and usually the only available way to loop!) func fib(num: Int) -> Int{ if(num == 0){ return 0; } if(num == 1){ return 1; } return fib(num - 1) + fib(num - 2); }
  13. RECURSION 47deg.com 15 To achieve recursion it’s usually needed to

    keep the accumulated results in a stack. This can be eluded by using tail-recursion, that allows compilers to optimize the calls and avoid using a stack. Unfortunately, in the current version of Swift tail- recursion is not guaranteed to be optimized . We hope this will change in the future!
  14. IMMUTABILITY 47deg.com 17 Immutable data types are always constant. How

    do we modify an immutable value then? By copying! When operating on immutable types, new modified copies are generated. As values are constant, the majority of the data can be shared between the copies to save memory. // Let’s imagine this is an immutable array: let iArray = [1, 2, 3, 4, 5] let iArrayExtra = iArray.append(6) // [1,2,3,4,5,6] let count = iArray.count // 5
  15. AVOIDING SIDE EFFECTS 47deg.com 18 func countBy(factor: Int, counter: Int)

    -> Int { if factor == 0 { return counter } return countBy(factor - 1, counter + 1) } Pure functions are not dependent on state func fillStack(stack: Stack<Int>, max: Int) -> Stack<Int> { if max == 0 { return stack } return fillStack(stack.push(max), max: max - 1) } fillStack(Stack<Int>(), withNumbersTil: 20) Immutable types can’t be modified by other threads We don’t need extensive control mechanisms to avoid problems with concurrency!
  16. Objective-C Swift Second Bridge Functs. 1st Class HOF Currying P.

    Matching Immutable types Improved P.Matching SWIFT IS MORE FUNCTIONAL THAN OBJECTIVE-C, BUT NOT ENOUGH
  17. INTRODUCTION TO SECOND BRIDGE 47deg.com 20 Second Bridge is a

    Swift framework that aims to cover these gaps, extending another great functional framework (Swiftz). http://47deg.github.io/second-bridge/ Open source Free to use Open for contributors
  18. IMMUTABLE DATA-TYPES: LISTT 47deg.com 21 ListT is an implementation of

    an immutable singly-linked list: the basic foundation of several other data types. let a : ListT<Int> = [1,2,3,4] let a1 = a.tail() // [2,3,4] let length = a.length() // 4 let a2 = a.filter({$0 % 3 != 0}) // [1,2,4]
  19. IMMUTABLE DATA-TYPES: ARRAYT 47deg.com 21 ArrayT is simply Swift’s Array

    made immutable! That is, its operations will always return another ArrayT instance. let a : ArrayT<Int> = [1,2,3,4,5,6] let a2 = anArray.drop(4) // [5,6] a.size() // 6
  20. IMMUTABLE DATA-TYPES: STACK 47deg.com 22 The same goes with Stack,

    which is an implementation of an immutable stack let s = Stack<Int>().push(1).push(2).push(3) let s2 = s.pop() // (3, Stack[2, 1])
  21. IMMUTABLE DATA-TYPES: MAP 47deg.com 23 Map behaves similarly as a

    Swift’s Dictionary, but: •It’s immutable •Supports several data-types for its keys (String, Int and Float) •Contains several custom operators for improved usability let m : Map<Int> = ["a" : 1, 2 : 2, 4.5 : 3] let m2 = m + [("foo", 7),("bar", 8)] let m3 = m2 --= ["foo", "bar"]
  22. IMMUTABLE DATE-TYPES: VECTOR 47deg.com 24 Update Prepend Append List Linear

    Constant Linear Stack Linear Constant Constant Queue Linear Linear Constant Vector near Constant near Constant near Constant (aka Persistent Bit-Partitioned Vector Trie)
  23. THE TRAVERSABLE AND ITERABLE PROTOCOLS 47deg.com 25 S Mapping/Filtering Grouping

    Partitioning collect groupBy dropWhile flatMap forAll split foldLeft mkString init mapConserve union split filter/filterNot take partition forAll zipAll sliding … and many more
  24. PARTIAL FUNCTIONS 47deg.com 26 Partial functions are those that only

    are defined for a certain set of values for each parameters. They allow us to query them for allowed parameters, to avoid calling them with a forbidden value (i.e. division by zero)
  25. PARTIAL FUNCTIONS OPERATORS 47deg.com 27 A great feature of partial

    functions is that they can be grouped to create more complex operation to define algorithms, by using the OR (|||>) and AND THEN (>>>) operators: let doubleEvens = { $0 % 2 == 0 } |-> { $0 * 2 } let tripleOdds = { $0 % 2 != 0 } |-> { $0 * 3 } let addFive = ∫(+5) let opOrElseOp = doubleEvens |||> tripleOdds let opOrElseAndThenOp = doubleEvens |||> tripleOdds >>> addFive opOrElseOp.apply(3) // 9 opOrElseOp.apply(4) // 8 opOrElseAndThenOp.apply(3) // 14 opOrElseAndThenOp.apply(4) // 13
  26. IMPROVED PATTERN MATCHING 47deg.com 28 Second Bridge’s partial functions also

    allows the use of a more complex and pure pattern matching than Swift’s. After evaluating its set of partial functions, the match function will return a value corresponding with the first recognized condition in the set. let matchTest = match({(item: Int) -> Bool in item == 0 } |-> {(Int) -> String in return "Zero"}, {(item: Int) -> Bool in item > 2 } |-> {(Int) -> String in return "Moar!"}) matchTest.apply(0) // "Zero" matchTest.apply(1000) // "Moar!"
  27. PLAYGROUND EXAMPLES 47deg.com 29 Second Bridge includes several Playgrounds bundled

    with the framework, including documented examples for its main features.
  28. SECOND BRIDGE - THE FUTURE 47deg.com 30 We want to

    keep helping Second Bridge to grow, and we’d really use your help! As this is a completely open-source project, to contribute you just have to access our repository. We’re looking forward to your PRs! http://47deg.github.io/second-bridge/
  29. LAMBDA WORLD 47deg.com 2 If you are interested in Functional

    Programming, no matter your level of expertise, we want to invite you to Lambda World on October 24th. It’s the largest Functional Programming event in Spain, sporting two tracks of conferences and workshops from real rockstar speakers! And all this happening in the beautiful city of Cádiz, one of the oldest towns in Europe! What’s to miss? For more details: www.lambda.world