Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Functional Programming Practice in Swift
Search
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
Hank Bao
January 10, 2016
Programming
120
4
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Functional Programming Practice in Swift
Swift 函数式编程实践
2016年1月10日在 @Swift 大会上的分享
Hank Bao
January 10, 2016
Transcript
38 slides
SWIFT ڍහୗᖫᑕ ਫ᪢
@HANKBAO ᅀIM
WHAT
WHAT Functional programming is a programming paradigm 1. treats computation
as the evaluation of mathematical functions 2. avoids changing-state and mutable data — Wikipedia
PARADIGM
None
THINK
IMPERATIVE: MACHINE let nums = [1, 2, 3, 4, 5,
6, 7] var strs = [String]() for var i = 0; i < nums.count; ++i { strs.append(String(nums[i])) }
DECLARATIVE: MATHEMATICS let nums = [1, 2, 3, 4, 5,
6, 7] let strs = nums.map(String.init)
WHY
CURRY
CURRY func x(a: A, b: B, c: C) -> E
func x(a: A) -> (b: B) -> (c: C) -> E
CURRY struct User { func login(password: String) } let passwd
= "@Swift" let usr = User() usr.login(passwd)
CURRY struct User { func login(password: String) } let passwd
= "@Swift" let usr = User() User.login(usr)(passwd)
CURRY usr.login(passwd) || User.login(usr)(passwd)
CURRY IN PRACTICE struct User { func name() -> String
} let collation: UILocalizedIndexedCollation = ... let sorted = collation.sortedArrayFromArray(users, collationStringSelector: "name")
CURRY IN PRACTICE class Wrapper<T>: NSObject { let payload: T
let localization: (T) -> () -> String @objc func localizable() -> NSString { return localization(payload)() } static var selector: Selector { return "localizable" } }
CURRY IN PRACTICE let wrappers = users.map { Wrapper(payload: $0,
localization: User.name) } let sorted = collation.sortedArrayFromArray(wrappers, collationStringSelector: Wrapper<User>.selector)
FUNCTIONAL ABSTRACTION
OPTIONAL enum Optional<T> { case None case Some(T) }
OPTIONAL func map<U>(f: T -> U) -> U? func flatMap<U>(f:
T -> U?) -> U? let date: NSDate? = ... let formatter: NSDateFormatter = ... let dateString = date.map(formatter.stringFromDate)
ARRAY func map<T>(t: Self.Generator.Element -> T) -> [T] func flatMap<S:
SequenceType> (t: Self.Generator.Element -> S) -> [S.Generator.Element]
MONAD<?>
MONAD<ASYNC>
PROMISE class Promise<T> { func then<U>(body: T -> U) ->
Promise<U> func then<U>(body: T -> Promise<U>) -> Promise<U> }
PROMISE class Promise<T> { func map<U>(body: T -> U) ->
Promise<U> func flatMap<U>(body: T -> Promise<U>) -> Promise<U> }
OBSERVABLE class Observable<T> { func map<U>(body: T -> U) ->
Observable<U> func flatMap<U>(body: T -> Observable<U>) -> Observable<U> }
MONAD IN PRACTICE
ASYNC CALLBACK (value: T?, error: ErrorType?) -> Void
ASYNC CALLBACK (value: T?, error: ErrorType?) -> Void if let
error = error { // handle error } else if let value = value { // handle value } else { // all nil? } // all non-nil?!
RESULT enum Result<Value> { case Failure(ErrorType) case Success(Value) }
RESULT (result: Result<T>) -> Void switch result { case let
.Error(error): // handle error case let .Success(value): // handle value }
RESULT enum Result<Value> { func map<T>(...) -> Result<T> { ...
} func flatMap<T>(...) -> Result<T> { ... } }
RESULT func flatMap<T>(@noescape transform: Value throws -> Result<T>) rethrows ->
Result<T> { switch self { case let .Failure(error): return .Failure(error) case let .Success(value): return try transform(value) } } func map<T>(@noescape transform: Value throws -> T) rethrows -> Result<T> { return try flatMap { .Success(try transform($0)) } }
RESULT func toImage(data: NSData) -> Result<UIImage> func addAlpha(image: UIImage) ->
Result<UIImage> func roundCorner(image: UIImage) -> Result<UIImage> func applyBlur(image: UIImage) -> Result<UIImage>
RESULT toImage(data) .flatMap(addAlpha) .flatMap(roundCorner) .flatMap(applyBlur)
REFERENCE ▸ Wikipedia ▸ Haskell Wiki ▸ Functional Programming in
Swift ▸ objc.io
THANKS Q & A
More Decks by Hank Bao
See All by Hank Bao
Notes on Gamification
hankbao
0
140
Reverse Engineering: from Objective-C to Swift
hankbao
2
480
Type-safe Programming Practice in Swift
hankbao
0
130
Other Decks in Programming
See All in Programming
社内AIエージェント「Askワンバン」における コストチューニングの取り組み
t0yohei
0
180
Kotlin JVM用に作られたライブラリのKMPを前提とした再設計
jsoizo
0
230
エージェントの管理もエージェントに – herdr-core と自作バックログで作る司令塔 –
nearme_tech
PRO
1
110
将来の標準フォーマッター?ktfmtを深堀る
t45k
0
250
LLM 101: Exploring LLMs, Starting with Tokens.
dalinaum
0
120
AWS CDKを理解するために公式の定義を深掘って解説してみる / Understanding AWS CDK by Digging into Its Official Definition
akihisaikeda
3
330
クラウドエージェントは、 何がそんなに便利なのか / what makes cloud agents so useful
rkaga
5
980
protojson における文字化けの扱い
kazuki1023
0
460
AI時代のシニアエンジニアとは
yosuke_furukawa
PRO
15
12k
flutter_test のその先へ — Flutter アプリの LLM 機能に「評価」という品質保証を
kosukesaigusa
0
210
AI時代のIaC入門 〜なぜインフラをコードで管理したいのか?〜 / Introduction to IaC in the AI Era
akihisaikeda
6
1.6k
[Kotlin Fest 2026] eBPF Tracing for Kotlin
takehaya
1
400
Featured
See All Featured
Breaking role norms: Why Content Design is so much more than writing copy - Taylor Woolridge
uxyall
2
540
Become a Pro
speakerdeck
PRO
31
6.4k
Navigating the Design Leadership Dip - Product Design Week Design Leaders+ Conference 2024
apolaine
2
530
Kristin Tynski - Automating Marketing Tasks With AI
techseoconnect
PRO
0
600
Introduction to Domain-Driven Design and Collaborative software design
baasie
1
1.1k
Producing Creativity
orderedlist
PRO
348
41k
sira's awesome portfolio website redesign presentation
elsirapls
0
520
Mobile First: as difficult as doing things right
swwweet
225
10k
Everyday Curiosity
cassininazir
0
420
Redefining SEO in the New Era of Traffic Generation
szymonslowik
1
540
How to Get Subject Matter Experts Bought In and Actively Contributing to SEO & PR Initiatives.
livdayseo
1
250
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
659
62k