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

SwiftのmapとflatMapを雑に解説する / map and flatMap on S...

Hiron
December 29, 2015

SwiftのmapとflatMapを雑に解説する / map and flatMap on Swift

tokushima.app で発表 **しなかった** スライドです。

2015年の年末あたりに、次のtokushima.appで発表しようと考えて作ったのですが、会場の都合でしばらく開かれなくて完全にタイミングを逃し、次に開かれたときには別のことを発表しました😓

Hiron

December 29, 2015
Tweet

More Decks by Hiron

Other Decks in Programming

Transcript

  1. "SSBZͷNBQ let array: [Int] = [1, 3, 8] array.map {x

    in x + 1}    f(x) f(x) f(x) f(x) = x + 1   
  2. "SSBZͷNBQ let array: [Int] = [1, 3, 8] array.map {x

    in [x, x + 1]}    f(x) f(x) f(x) f(x) = [x, x + 1]      
  3. "SSBZͷqBU.BQ let array: [Int] = [1, 3, 8] array.flatMap {x

    in [x, x + 1]}    f(x) f(x) f(x) f(x) = [x, x + 1]      
  4. 0QUJPOBMͷNBQ let value: Int? = … value.map {x in x

    + 1} let value: Int? = 16 value.map {x in x + 1}  f(x)  let value: Int? = nil value.map {x in x + 1} OJM OJM
  5. NBQ let array: [Int] = [] array.map {x in x

    + 1} -> [] let array: [Int] = [16] array.map {x in x + 1} -> [17] let value: Int? = nil value.map {x in x + 1} -> nil let value: Int? = 16 …Int?(16) value.map {x in x + 1} -> 17 …Int?(17)
  6. qBU.BQ let array: [Int] = [] array.flatMap {x in [x

    + 1]} -> [] let array: [Int] = [16] array.flatMap {x in [x + 1]} -> [17] let value: Int? = nil value.flatMap {x in Int?(x + 1)} -> nil let value: Int? = 16 …Int?(16) value.flatMap {x in Int?(x + 1)} -> 17 …Int?(17)
  7. 0QUJPOBMͷqBU.BQ let value: Int? = … value.flatMap {x -> Int?

    in if (x < 1) { return nil // ܭࢉࣦഊ } else { return x - 1 } }
  8. ·ͱΊ func plusOne(x: Int) -> Int { return x +

    1 } let array: [Int] = [1, 3, 8] array.map(plusOne) let value: Int? = 16 value.map(plusOne) w NBQ͸ശ͔Βग़ͯ͠ɺؔ਺Λద༻ ͯ͠ശʹೖΕΔɻ w qBU.BQ͸ശ͔Βग़ͯ͠ɺؔ਺Λ ద༻ͯ͠ϑϥοτʹശʹೖΕΔɻ w NBQ qBU.BQΛ࢖͏ͱɺͦ͜ʹ ౉͞ΕΔؔ਺͸֎ଆͷੈքΛҙࣝ ͠ͳ͍͍ͯ͘ʂ