Lock in $30 Savings on PRO—Offer Ends Soon! ⏳

Functional Swift

Functional Swift

Presented at NSCoder Night Copenhagen

Avatar for Ulrik Flænø Damm

Ulrik Flænø Damm

July 23, 2014
Tweet

Other Decks in Programming

Transcript

  1. Int -> Int func sqr(i : Int) -> Int {

    return i * i } { i in i * i } ~
  2. 1 2 ff 2e ad load value to a load

    value to b > add a and b and store in c print value c
  3. MAP

  4. MAP & REDUCE 1 2 3 1 4 9 0

    14 (((0 + 1) + 4) + 9) = 14 sqr sqr sqr + + + =
  5. IN SWIFT func map<U>(transform: (T) -> U) -> [U] func

    reduce<U>(initial: U, combine: (U, T) -> U) -> U
  6. IN SWIFT [1, 2, 3].map { value in value +

    1 } [1, 2, 3].reduce(0) { result, value in result + value }
  7. CLOSURE SYNTAX let closure : (Int, Int) -> Int =

    { value1, value2 -> Int in return value1 + value2 } [1, 2, 3].reduce(0, closure)
  8. AVERAGE let values = [5, 8, 17] // procedural var

    sum = 0 for value in values { sum += value } let average = sum / values.count // functional values.reduce(0, +) / values.count
  9. COUNT OCCURENCES func count_occurences(vals : [Int], of val : Int)

    -> Int { return vals.reduce(0) { count, this in return count + (val == this ? 1 : 0) } }
  10. CONTAINS func contains(vals : [Int], find val : Int) ->

    Bool { return vals.reduce(false) { found, this in if found { return true } else { return val == this } } }
  11. WORDBASE func createPositions(positions : (Int, Int)...) -> [Position] { return

    positions.map { position in return Position(x: position.0, y: position.1) } } func wordFromTiles(tiles : [Position]) -> String { return tiles.reduce("") { string, position in return string + self.characterAtPosition(position) } }
  12. TYPE INFERENCE let ns = [1, 2, 3] ns.reduce(0, +)

    // 6 let ss = ["1", "2", "3"] ss.reduce("", +) // “123" let moves = [(0,1) => (0,2), (5, 7) => (7, 7)] moves.reduce(ChessBoard(), +)
  13. FIN