Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Functional Programming Practice in Swift
Search
Hank Bao
January 10, 2016
Programming
4
110
Functional Programming Practice in Swift
Swift 函数式编程实践
2016年1月10日在 @Swift 大会上的分享
Hank Bao
January 10, 2016
Tweet
Share
More Decks by Hank Bao
See All by Hank Bao
Notes on Gamification
hankbao
0
120
Reverse Engineering: from Objective-C to Swift
hankbao
2
440
Type-safe Programming Practice in Swift
hankbao
0
110
Other Decks in Programming
See All in Programming
システム成長を止めない!本番無停止テーブル移行の全貌
sakawe_ee
1
160
Google Agent Development Kit でLINE Botを作ってみた
ymd65536
2
220
PicoRuby on Rails
makicamel
2
120
Porting a visionOS App to Android XR
akkeylab
0
260
関数型まつりレポート for JuliaTokai #22
antimon2
0
160
“いい感じ“な定量評価を求めて - Four Keysとアウトカムの間の探求 -
nealle
1
7.2k
High-Level Programming Languages in AI Era -Human Thought and Mind-
hayat01sh1da
PRO
0
720
たった 1 枚の PHP ファイルで実装する MCP サーバ / MCP Server with Vanilla PHP
okashoi
1
230
Railsアプリケーションと パフォーマンスチューニング ー 秒間5万リクエストの モバイルオーダーシステムを支える事例 ー Rubyセミナー 大阪
falcon8823
5
1.1k
Quand Symfony, ApiPlatform, OpenAI et LangChain s'allient pour exploiter vos PDF : de la théorie à la production…
ahmedbhs123
0
130
Hypervel - A Coroutine Framework for Laravel Artisans
albertcht
1
110
初学者でも今すぐできる、Claude Codeの生産性を10倍上げるTips
s4yuba
14
9.6k
Featured
See All Featured
How to train your dragon (web standard)
notwaldorf
94
6.1k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
45
7.5k
Learning to Love Humans: Emotional Interface Design
aarron
273
40k
Testing 201, or: Great Expectations
jmmastey
42
7.6k
Chrome DevTools: State of the Union 2024 - Debugging React & Beyond
addyosmani
7
730
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
194
16k
Documentation Writing (for coders)
carmenintech
72
4.9k
Facilitating Awesome Meetings
lara
54
6.4k
Fashionably flexible responsive web design (full day workshop)
malarkey
407
66k
The Language of Interfaces
destraynor
158
25k
Music & Morning Musume
bryan
46
6.6k
Practical Orchestrator
shlominoach
188
11k
Transcript
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