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

Elements of Functional Programming

Paul Hudson
January 29, 2018

Elements of Functional Programming

Delivered at dotSwift 2018: Functional programming might seem scary at first, but with some hands-on examples you'll soon find you can use map(), flatMap(), filter(), and more in your own projects and see some real benefits.

Presented at dotSwift 2018, Paris.

Paul Hudson

January 29, 2018
Tweet

More Decks by Paul Hudson

Other Decks in Programming

Transcript

  1. MAP

  2. var result = [Int]() for string in strings { result.append(string.count)

    } return result func lengthOf(strings: [String]) -> [Int] { }
  3. func map<T>(_ transform: (Element) -> T) -> [T] { var

    returnValue = [T]() for item in self { returnValue.append(transform(item)) } return returnValue }
  4. let greet = name.map { “Hi, \($0)!” } print(greet ??

    “Unknown user”) let name: String? = getUser(id: 97)
  5. let greet: String if let name = name { greet

    = "Hi, \(name)!" } else { greet = "Unknown user" } print(greet) let name: String? = getUser(id: 97)
  6. let numbers = [1, 2, 3, 4, 5] let odd

    = numbers.filter { $0 % 2 == 1 }
  7. let ints = [9, 5, 3, 5] let counts =

    ints.map { ($0, 1) } // [(9, 1), (5, 1), (3, 1), (5, 1)] let dict = Dictionary(counts, uniquingKeysWith: +) // [9: 1, 5: 2, 3: 1]
  8. let yes = [“oui”, “ouais”, “bien sûr”] let reply =

    “ma réponse est oui” yes.contains(where: reply.contains)