SlideShare a Scribd company logo
. ) . . ( .
)
-
.
let n = 42
42 func function(_ i: Int) -> Int {
return i + 42
}
let f = function
type(of: n)
// Int
type(of: f)
// (Int) -> Int
let n: Int = 42 let f: (Int) -> Int = function
let f: (Int) -> Int = { i in
return i + 42
}
Value Function
f(21)21 + n
Function
func output(_ i: Int) {
print(i)
}
output(n)
func output(_ i: Int,
_ m: (Int) -> Int)
{
print(m(i))
}
output(21, f)
func getN() -> Int {
let n = 42
return n
}
func getF() -> (Int) -> Int {
let f = { $0 + 42 }
return f
}
Value
Higher-Order Functions
func fs1(_ f: (((Int) -> Int) -> Int) -> Int) {
}
func fs2() -> (Int) -> (Int) -> (Int) -> Int {
}
Sync Action
@discardableResult
func createView<V : UIView>(_ view: V,
_ parent: UIView?,
_ setter: (V) -> Void) -> V {
parent?.addSubview(view)
setter(view)
return view
}
createView(UIImageView(), view) { iv in
iv.contentMode = .scaleAspectFill
iv.clipsToBounds = true
iv.layer.cornerRadius = 16
iv.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
}
func downloadImage(from url: URL,
completion: @escaping (UIImage?) -> Void)
{
DispatchQueue.main.async {
if let image = try? UIImage(data: Data(contentsOf: url)) {
completion(image)
} else {
completion(nil)
}
}
}
downloadImage(from: URL(string: "image download url")!,
completion: { img in
self.imageView.image = img
})
Async Action
{
let fadeOutAlpha: CGFloat = 0
UIView.animate(withDuration: 0.3,
animations: {
self.button.alpha = fadeOutAlpha
},
completion: { completed in
self.button.isHidden = true
})
}
Closure
extension UIView {
@available(iOS 4.0, *)
open class func animate(withDuration duration: TimeInterval,
animations: @escaping () -> Void,
completion: ((Bool) -> Void)? = nil)
}
func downloadImage(completion: @escaping (UIImage?) -> Void)
{
DispatchQueue.main.async {
let url = URL(string: "image download url")!
let image = try! UIImage(data: Data(contentsOf: url))
completion(image)
}
}
Generalize
func gafunction(_ task: ((T) -> Void) -> Void) {
DispatchQueue.main.async {
task(job)
}
}
gaFunction(task: { f in
let url = URL(string: "image download url")!
let image = try! UIImage(data: Data(contentsOf: url))
f(image)
}, execute: { img in
self.imageView.image = img
})
func gaFunction<T>(task: @escaping ((@escaping (T) -> Void) -> Void),
execute: @escaping (T) -> Void)
{
DispatchQueue.main.async {
task(execute)
}
}
General Async Function
General Async Function Class
class GAFunction<T> {
private let task: ((@escaping (T) -> Void) -> Void)
init(task: @escaping (@escaping (T) -> Void) -> Void) {
self.task = task
}
func execute(_ f: @escaping (T) -> Void) {
DispatchQueue.main.async {
self.task(f)
}
}
}
class GAFunction<T> {
private let task: ((@escaping (T) -> Void) -> Void)
init(task job: @escaping (@escaping (T) -> Void) -> Void) {
task = job
}
func execute(_ f: @escaping (T) -> Void) {
DispatchQueue.main.async {
self.task(f)
}
}
}
GAFunction class
let gaf = GAFunction<UIImage?>(task: { f in
let url = URL(string: "image download url")!
let image = try! UIImage(data: Data(contentsOf: url))
f(image)
})
gaf.execute({ img in
self.imageView.image = img
})
Async Value
//42
//41
//40
extension GAFunction {
convenience init(just t: T) {
self.init(task: { f in f(t) })
}
convenience init(from ts: [T]) {
self.init(task: { f in ts.forEach(f) })
}
}
GAFunction(just: 42)
.execute({ i in
print(i)
})
GAFunction(from: [42, 41, 40])
.execute({ i in
print(i)
})
//42
Filter
//42
//40
//38
extension GAFunction {
func filter(_ filter: @escaping (T) -> Bool) -> GAFunction<T> {
return GAFunction<T>(task: { f in
self.execute({ t in
if filter(t) {
f(t)
}
})
})
}
}
GAFunction(from: [42, 41, 40, 39, 38])
.filter({ $0 % 2 == 0 })
.execute({ i in
print(i)
})
Map
//420
//410
//400
extension GAFunction {
func map<U>(_ mapper: @escaping (T) -> U) -> GAFunction<U> {
return GAFunction<U>(task: { f in
self.execute({ t in
f(mapper(t))
})
})
}
}
GAFunction(from: [42, 41, 40])
.map({ $0 * 10 })
.execute({ i in
print(i)
})
FlatMap
extension GAFunction {
public func flatMap<U>(_ mapper: @escaping (T) -> GAFunction<U>)
-> GAFunction<U>
{
return GAFunction<U>(task: { f in
self.execute({ t in
mapper(t).execute({ u in f(u) })
})
})
}
}
GAFunction(from: [42, 41, 40])
.flatMap({ i -> GAFunction<Float> in
GAFunction(just: Float(i) / 3)
})
.execute({ f in
print(f)
})
//14.0
//13.666667
//13.333333
All together
GAFunction(just: "image url")
.map({ URL(string: $0) })
.filter({ $0 != nil })
.map({ $0! })
.flatMap(downloadImage)
.execute({ img in
self.imageView.image = img
})
func downloadImage(_ url: URL) -> GAFunction<UIImage?> {
return GAFunction(task: { completion in
if let image = try? UIImage(data: Data(contentsOf: url)) {
completion(image)
} else {
completion(nil)
}
})
}
All together
GAFunction(just: "image url")
.map({ URL(string: $0) })
.filter({ $0 != nil })
.map({ $0! })
.flatMap(downloadImage)
.execute({ img in
self.imageView.image = img
})
func downloadImage(_ url: URL) -> GAFunction<UIImage?> {
return GAFunction(task: { completion in
if let image = try? UIImage(data: Data(contentsOf: url)) {
completion(image)
} else {
completion(nil)
}
})
}
Summary
1. 함수는 value 처럼

- 변수에 담을 수 있다

- 파라미터로 넘길 수 있다

- 리턴값으로 반환될 수 있다

2. 고차함수(Higher-Order Function)

- 함수가 파라미터로 쓰이거나 반환값으로 사용되는 경우

- 전달된 함수가 본체의 수행이 종료된 후에 사용되는 경우 @escaping을 해줘야 한다.

- optional function 은 @escaping이 기본이다.

3. 함수는 행동을 저장한다

- 저장한 행동은 전달될 수 있다.

- 저장된 행동은 나중에 사용될 수 있다.

4. 이러한 특성들로 여러 재밌는 것들을 만들 수 있다.

- 사례. GAFunction

5. 이미 이러한 성질을 이용해서 범용으로 만들어진 라이브러리가 있다.

- RxSwift 를 쓰자
광고

More Related Content

What's hot

Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
Eugene Zharkov
 
UIKonf App & Data Driven Design @swift.berlin
UIKonf App & Data Driven Design @swift.berlinUIKonf App & Data Driven Design @swift.berlin
UIKonf App & Data Driven Design @swift.berlin
Maxim Zaks
 
ZIO Queue
ZIO QueueZIO Queue
Blocks+gcd入門
Blocks+gcd入門Blocks+gcd入門
Blocks+gcd入門
領一 和泉田
 
GoLightly - a customisable virtual machine written in Go
GoLightly - a customisable virtual machine written in GoGoLightly - a customisable virtual machine written in Go
GoLightly - a customisable virtual machine written in Go
Eleanor McHugh
 
Designing Immutability Data Flows in Ember
Designing Immutability Data Flows in EmberDesigning Immutability Data Flows in Ember
Designing Immutability Data Flows in Ember
Jorge Lainfiesta
 
Drinking the free kool-aid
Drinking the free kool-aidDrinking the free kool-aid
Drinking the free kool-aid
David Hoyt
 
Berlin meetup
Berlin meetupBerlin meetup
Berlin meetup
Wiem Zine Elabidine
 
mobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkelingmobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkelingDevnology
 
CBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical fileCBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical file
Pranav Ghildiyal
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FP
Luka Jacobowitz
 
Pure Future
Pure FuturePure Future
Pure Future
Wiem Zine Elabidine
 
C++ TUTORIAL 8
C++ TUTORIAL 8C++ TUTORIAL 8
C++ TUTORIAL 8
Farhan Ab Rahman
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentation
Martin McBride
 
Fiber supervision in ZIO
Fiber supervision in ZIOFiber supervision in ZIO
Fiber supervision in ZIO
Wiem Zine Elabidine
 
C++ TUTORIAL 6
C++ TUTORIAL 6C++ TUTORIAL 6
C++ TUTORIAL 6
Farhan Ab Rahman
 
Part2 from math import * from simpson import * k=1 def f(x): return (exp(-(x...
Part2 from math import * from simpson import *  k=1 def f(x): return (exp(-(x...Part2 from math import * from simpson import *  k=1 def f(x): return (exp(-(x...
Part2 from math import * from simpson import * k=1 def f(x): return (exp(-(x...
hwbloom25
 
C++ TUTORIAL 7
C++ TUTORIAL 7C++ TUTORIAL 7
C++ TUTORIAL 7
Farhan Ab Rahman
 
Effector: we need to go deeper
Effector: we need to go deeperEffector: we need to go deeper
Effector: we need to go deeper
Victor Didenko
 

What's hot (20)

Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
 
UIKonf App & Data Driven Design @swift.berlin
UIKonf App & Data Driven Design @swift.berlinUIKonf App & Data Driven Design @swift.berlin
UIKonf App & Data Driven Design @swift.berlin
 
ZIO Queue
ZIO QueueZIO Queue
ZIO Queue
 
Blocks+gcd入門
Blocks+gcd入門Blocks+gcd入門
Blocks+gcd入門
 
GoLightly - a customisable virtual machine written in Go
GoLightly - a customisable virtual machine written in GoGoLightly - a customisable virtual machine written in Go
GoLightly - a customisable virtual machine written in Go
 
Designing Immutability Data Flows in Ember
Designing Immutability Data Flows in EmberDesigning Immutability Data Flows in Ember
Designing Immutability Data Flows in Ember
 
Drinking the free kool-aid
Drinking the free kool-aidDrinking the free kool-aid
Drinking the free kool-aid
 
Berlin meetup
Berlin meetupBerlin meetup
Berlin meetup
 
mobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkelingmobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkeling
 
CBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical fileCBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical file
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FP
 
Pure Future
Pure FuturePure Future
Pure Future
 
C++ TUTORIAL 8
C++ TUTORIAL 8C++ TUTORIAL 8
C++ TUTORIAL 8
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentation
 
Fiber supervision in ZIO
Fiber supervision in ZIOFiber supervision in ZIO
Fiber supervision in ZIO
 
C++ TUTORIAL 6
C++ TUTORIAL 6C++ TUTORIAL 6
C++ TUTORIAL 6
 
Part2 from math import * from simpson import * k=1 def f(x): return (exp(-(x...
Part2 from math import * from simpson import *  k=1 def f(x): return (exp(-(x...Part2 from math import * from simpson import *  k=1 def f(x): return (exp(-(x...
Part2 from math import * from simpson import * k=1 def f(x): return (exp(-(x...
 
Opp compile
Opp compileOpp compile
Opp compile
 
C++ TUTORIAL 7
C++ TUTORIAL 7C++ TUTORIAL 7
C++ TUTORIAL 7
 
Effector: we need to go deeper
Effector: we need to go deeperEffector: we need to go deeper
Effector: we need to go deeper
 

Similar to 20181020 advanced higher-order function

20191116 custom operators in swift
20191116 custom operators in swift20191116 custom operators in swift
20191116 custom operators in swift
Chiwon Song
 
Go: It's Not Just For Google
Go: It's Not Just For GoogleGo: It's Not Just For Google
Go: It's Not Just For Google
Eleanor McHugh
 
Kotlin for android developers whats new
Kotlin for android developers whats newKotlin for android developers whats new
Kotlin for android developers whats new
Serghii Chaban
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit partsMaxim Zaks
 
Monadologie
MonadologieMonadologie
Monadologie
league
 
Functional JS for everyone - 4Developers
Functional JS for everyone - 4DevelopersFunctional JS for everyone - 4Developers
Functional JS for everyone - 4Developers
Bartek Witczak
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
Hermann Hueck
 
Taming Asynchronous Transforms with Interstellar
Taming Asynchronous Transforms with InterstellarTaming Asynchronous Transforms with Interstellar
Taming Asynchronous Transforms with Interstellar
Jens Ravens
 
(Fun)ctional go
(Fun)ctional go(Fun)ctional go
(Fun)ctional go
BenJanecke
 
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with SwiftStanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
진성 오
 
Rのスコープとフレームと環境と
Rのスコープとフレームと環境とRのスコープとフレームと環境と
Rのスコープとフレームと環境と
Takeshi Arabiki
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
Vincent Pradeilles
 
Functional JavaScript for everyone
Functional JavaScript for everyoneFunctional JavaScript for everyone
Functional JavaScript for everyone
Bartek Witczak
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
Calvin Cheng
 
lets play with "c"..!!! :):)
lets play with "c"..!!! :):)lets play with "c"..!!! :):)
lets play with "c"..!!! :):)
Rupendra Choudhary
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
Sergey Bandysik
 
The Strange World of Javascript and all its little Asynchronous Beasts
The Strange World of Javascript and all its little Asynchronous BeastsThe Strange World of Javascript and all its little Asynchronous Beasts
The Strange World of Javascript and all its little Asynchronous Beasts
Federico Galassi
 
FS2 for Fun and Profit
FS2 for Fun and ProfitFS2 for Fun and Profit
FS2 for Fun and Profit
Adil Akhter
 

Similar to 20181020 advanced higher-order function (20)

20191116 custom operators in swift
20191116 custom operators in swift20191116 custom operators in swift
20191116 custom operators in swift
 
Go: It's Not Just For Google
Go: It's Not Just For GoogleGo: It's Not Just For Google
Go: It's Not Just For Google
 
Kotlin for android developers whats new
Kotlin for android developers whats newKotlin for android developers whats new
Kotlin for android developers whats new
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit parts
 
Monadologie
MonadologieMonadologie
Monadologie
 
Functional JS for everyone - 4Developers
Functional JS for everyone - 4DevelopersFunctional JS for everyone - 4Developers
Functional JS for everyone - 4Developers
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
 
Taming Asynchronous Transforms with Interstellar
Taming Asynchronous Transforms with InterstellarTaming Asynchronous Transforms with Interstellar
Taming Asynchronous Transforms with Interstellar
 
(Fun)ctional go
(Fun)ctional go(Fun)ctional go
(Fun)ctional go
 
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with SwiftStanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
Rのスコープとフレームと環境と
Rのスコープとフレームと環境とRのスコープとフレームと環境と
Rのスコープとフレームと環境と
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
Functional JavaScript for everyone
Functional JavaScript for everyoneFunctional JavaScript for everyone
Functional JavaScript for everyone
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 
lets play with "c"..!!! :):)
lets play with "c"..!!! :):)lets play with "c"..!!! :):)
lets play with "c"..!!! :):)
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
 
The Strange World of Javascript and all its little Asynchronous Beasts
The Strange World of Javascript and all its little Asynchronous BeastsThe Strange World of Javascript and all its little Asynchronous Beasts
The Strange World of Javascript and all its little Asynchronous Beasts
 
FS2 for Fun and Profit
FS2 for Fun and ProfitFS2 for Fun and Profit
FS2 for Fun and Profit
 

More from Chiwon Song

20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기
Chiwon Song
 
요즘 유행하는 AI 나도 해보자 (feat. CoreML)
요즘 유행하는 AI 나도 해보자 (feat. CoreML)요즘 유행하는 AI 나도 해보자 (feat. CoreML)
요즘 유행하는 AI 나도 해보자 (feat. CoreML)
Chiwon Song
 
20220716_만들면서 느껴보는 POP
20220716_만들면서 느껴보는 POP20220716_만들면서 느껴보는 POP
20220716_만들면서 느껴보는 POP
Chiwon Song
 
20210812 컴퓨터는 어떻게 동작하는가?
20210812 컴퓨터는 어떻게 동작하는가?20210812 컴퓨터는 어떻게 동작하는가?
20210812 컴퓨터는 어떻게 동작하는가?
Chiwon Song
 
20201121 코드 삼분지계
20201121 코드 삼분지계20201121 코드 삼분지계
20201121 코드 삼분지계
Chiwon Song
 
20200815 inversions
20200815 inversions20200815 inversions
20200815 inversions
Chiwon Song
 
[20190601] 직업훈련교사_수업의실행_교안
[20190601] 직업훈련교사_수업의실행_교안[20190601] 직업훈련교사_수업의실행_교안
[20190601] 직업훈련교사_수업의실행_교안
Chiwon Song
 
[20190601] 직업훈련교사_수업의실행
[20190601] 직업훈련교사_수업의실행[20190601] 직업훈련교사_수업의실행
[20190601] 직업훈련교사_수업의실행
Chiwon Song
 
20190330 immutable data
20190330 immutable data20190330 immutable data
20190330 immutable data
Chiwon Song
 
20190306 만들면서 배우는 IoT / IoT의 이해
20190306 만들면서 배우는 IoT / IoT의 이해20190306 만들면서 배우는 IoT / IoT의 이해
20190306 만들면서 배우는 IoT / IoT의 이해
Chiwon Song
 
20171104 FRP 패러다임
20171104 FRP 패러다임20171104 FRP 패러다임
20171104 FRP 패러다임
Chiwon Song
 
스크래치로 시작하는 코딩
스크래치로 시작하는 코딩스크래치로 시작하는 코딩
스크래치로 시작하는 코딩
Chiwon Song
 
메이커운동과 아두이노
메이커운동과 아두이노메이커운동과 아두이노
메이커운동과 아두이노
Chiwon Song
 
아두이노 RC카 만들기
아두이노 RC카 만들기아두이노 RC카 만들기
아두이노 RC카 만들기
Chiwon Song
 
[5] 아두이노로 만드는 IoT
[5] 아두이노로 만드는 IoT[5] 아두이노로 만드는 IoT
[5] 아두이노로 만드는 IoT
Chiwon Song
 
[4] 아두이노와 인터넷
[4] 아두이노와 인터넷[4] 아두이노와 인터넷
[4] 아두이노와 인터넷
Chiwon Song
 
[2] 아두이노 활용 실습
[2] 아두이노 활용 실습[2] 아두이노 활용 실습
[2] 아두이노 활용 실습
Chiwon Song
 
[3] 프로세싱과 아두이노
[3] 프로세싱과 아두이노[3] 프로세싱과 아두이노
[3] 프로세싱과 아두이노
Chiwon Song
 
[1] IoT와 아두이노
[1] IoT와 아두이노[1] IoT와 아두이노
[1] IoT와 아두이노
Chiwon Song
 
3D 프린터와 아두이노
3D 프린터와 아두이노3D 프린터와 아두이노
3D 프린터와 아두이노
Chiwon Song
 

More from Chiwon Song (20)

20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기20240330_고급진 코드를 위한 exception 다루기
20240330_고급진 코드를 위한 exception 다루기
 
요즘 유행하는 AI 나도 해보자 (feat. CoreML)
요즘 유행하는 AI 나도 해보자 (feat. CoreML)요즘 유행하는 AI 나도 해보자 (feat. CoreML)
요즘 유행하는 AI 나도 해보자 (feat. CoreML)
 
20220716_만들면서 느껴보는 POP
20220716_만들면서 느껴보는 POP20220716_만들면서 느껴보는 POP
20220716_만들면서 느껴보는 POP
 
20210812 컴퓨터는 어떻게 동작하는가?
20210812 컴퓨터는 어떻게 동작하는가?20210812 컴퓨터는 어떻게 동작하는가?
20210812 컴퓨터는 어떻게 동작하는가?
 
20201121 코드 삼분지계
20201121 코드 삼분지계20201121 코드 삼분지계
20201121 코드 삼분지계
 
20200815 inversions
20200815 inversions20200815 inversions
20200815 inversions
 
[20190601] 직업훈련교사_수업의실행_교안
[20190601] 직업훈련교사_수업의실행_교안[20190601] 직업훈련교사_수업의실행_교안
[20190601] 직업훈련교사_수업의실행_교안
 
[20190601] 직업훈련교사_수업의실행
[20190601] 직업훈련교사_수업의실행[20190601] 직업훈련교사_수업의실행
[20190601] 직업훈련교사_수업의실행
 
20190330 immutable data
20190330 immutable data20190330 immutable data
20190330 immutable data
 
20190306 만들면서 배우는 IoT / IoT의 이해
20190306 만들면서 배우는 IoT / IoT의 이해20190306 만들면서 배우는 IoT / IoT의 이해
20190306 만들면서 배우는 IoT / IoT의 이해
 
20171104 FRP 패러다임
20171104 FRP 패러다임20171104 FRP 패러다임
20171104 FRP 패러다임
 
스크래치로 시작하는 코딩
스크래치로 시작하는 코딩스크래치로 시작하는 코딩
스크래치로 시작하는 코딩
 
메이커운동과 아두이노
메이커운동과 아두이노메이커운동과 아두이노
메이커운동과 아두이노
 
아두이노 RC카 만들기
아두이노 RC카 만들기아두이노 RC카 만들기
아두이노 RC카 만들기
 
[5] 아두이노로 만드는 IoT
[5] 아두이노로 만드는 IoT[5] 아두이노로 만드는 IoT
[5] 아두이노로 만드는 IoT
 
[4] 아두이노와 인터넷
[4] 아두이노와 인터넷[4] 아두이노와 인터넷
[4] 아두이노와 인터넷
 
[2] 아두이노 활용 실습
[2] 아두이노 활용 실습[2] 아두이노 활용 실습
[2] 아두이노 활용 실습
 
[3] 프로세싱과 아두이노
[3] 프로세싱과 아두이노[3] 프로세싱과 아두이노
[3] 프로세싱과 아두이노
 
[1] IoT와 아두이노
[1] IoT와 아두이노[1] IoT와 아두이노
[1] IoT와 아두이노
 
3D 프린터와 아두이노
3D 프린터와 아두이노3D 프린터와 아두이노
3D 프린터와 아두이노
 

Recently uploaded

Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 

Recently uploaded (20)

Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 

20181020 advanced higher-order function

  • 1. . ) . . ( . ) - .
  • 2.
  • 3. let n = 42 42 func function(_ i: Int) -> Int { return i + 42 } let f = function type(of: n) // Int type(of: f) // (Int) -> Int let n: Int = 42 let f: (Int) -> Int = function let f: (Int) -> Int = { i in return i + 42 } Value Function f(21)21 + n
  • 4. Function func output(_ i: Int) { print(i) } output(n) func output(_ i: Int, _ m: (Int) -> Int) { print(m(i)) } output(21, f) func getN() -> Int { let n = 42 return n } func getF() -> (Int) -> Int { let f = { $0 + 42 } return f } Value
  • 5. Higher-Order Functions func fs1(_ f: (((Int) -> Int) -> Int) -> Int) { } func fs2() -> (Int) -> (Int) -> (Int) -> Int { }
  • 6.
  • 7. Sync Action @discardableResult func createView<V : UIView>(_ view: V, _ parent: UIView?, _ setter: (V) -> Void) -> V { parent?.addSubview(view) setter(view) return view } createView(UIImageView(), view) { iv in iv.contentMode = .scaleAspectFill iv.clipsToBounds = true iv.layer.cornerRadius = 16 iv.frame = CGRect(x: 0, y: 0, width: 100, height: 100) }
  • 8. func downloadImage(from url: URL, completion: @escaping (UIImage?) -> Void) { DispatchQueue.main.async { if let image = try? UIImage(data: Data(contentsOf: url)) { completion(image) } else { completion(nil) } } } downloadImage(from: URL(string: "image download url")!, completion: { img in self.imageView.image = img }) Async Action
  • 9. { let fadeOutAlpha: CGFloat = 0 UIView.animate(withDuration: 0.3, animations: { self.button.alpha = fadeOutAlpha }, completion: { completed in self.button.isHidden = true }) } Closure extension UIView { @available(iOS 4.0, *) open class func animate(withDuration duration: TimeInterval, animations: @escaping () -> Void, completion: ((Bool) -> Void)? = nil) }
  • 10.
  • 11. func downloadImage(completion: @escaping (UIImage?) -> Void) { DispatchQueue.main.async { let url = URL(string: "image download url")! let image = try! UIImage(data: Data(contentsOf: url)) completion(image) } } Generalize func gafunction(_ task: ((T) -> Void) -> Void) { DispatchQueue.main.async { task(job) } }
  • 12. gaFunction(task: { f in let url = URL(string: "image download url")! let image = try! UIImage(data: Data(contentsOf: url)) f(image) }, execute: { img in self.imageView.image = img }) func gaFunction<T>(task: @escaping ((@escaping (T) -> Void) -> Void), execute: @escaping (T) -> Void) { DispatchQueue.main.async { task(execute) } } General Async Function
  • 13. General Async Function Class class GAFunction<T> { private let task: ((@escaping (T) -> Void) -> Void) init(task: @escaping (@escaping (T) -> Void) -> Void) { self.task = task } func execute(_ f: @escaping (T) -> Void) { DispatchQueue.main.async { self.task(f) } } }
  • 14. class GAFunction<T> { private let task: ((@escaping (T) -> Void) -> Void) init(task job: @escaping (@escaping (T) -> Void) -> Void) { task = job } func execute(_ f: @escaping (T) -> Void) { DispatchQueue.main.async { self.task(f) } } } GAFunction class let gaf = GAFunction<UIImage?>(task: { f in let url = URL(string: "image download url")! let image = try! UIImage(data: Data(contentsOf: url)) f(image) }) gaf.execute({ img in self.imageView.image = img })
  • 15. Async Value //42 //41 //40 extension GAFunction { convenience init(just t: T) { self.init(task: { f in f(t) }) } convenience init(from ts: [T]) { self.init(task: { f in ts.forEach(f) }) } } GAFunction(just: 42) .execute({ i in print(i) }) GAFunction(from: [42, 41, 40]) .execute({ i in print(i) }) //42
  • 16. Filter //42 //40 //38 extension GAFunction { func filter(_ filter: @escaping (T) -> Bool) -> GAFunction<T> { return GAFunction<T>(task: { f in self.execute({ t in if filter(t) { f(t) } }) }) } } GAFunction(from: [42, 41, 40, 39, 38]) .filter({ $0 % 2 == 0 }) .execute({ i in print(i) })
  • 17. Map //420 //410 //400 extension GAFunction { func map<U>(_ mapper: @escaping (T) -> U) -> GAFunction<U> { return GAFunction<U>(task: { f in self.execute({ t in f(mapper(t)) }) }) } } GAFunction(from: [42, 41, 40]) .map({ $0 * 10 }) .execute({ i in print(i) })
  • 18. FlatMap extension GAFunction { public func flatMap<U>(_ mapper: @escaping (T) -> GAFunction<U>) -> GAFunction<U> { return GAFunction<U>(task: { f in self.execute({ t in mapper(t).execute({ u in f(u) }) }) }) } } GAFunction(from: [42, 41, 40]) .flatMap({ i -> GAFunction<Float> in GAFunction(just: Float(i) / 3) }) .execute({ f in print(f) }) //14.0 //13.666667 //13.333333
  • 19. All together GAFunction(just: "image url") .map({ URL(string: $0) }) .filter({ $0 != nil }) .map({ $0! }) .flatMap(downloadImage) .execute({ img in self.imageView.image = img }) func downloadImage(_ url: URL) -> GAFunction<UIImage?> { return GAFunction(task: { completion in if let image = try? UIImage(data: Data(contentsOf: url)) { completion(image) } else { completion(nil) } }) }
  • 20. All together GAFunction(just: "image url") .map({ URL(string: $0) }) .filter({ $0 != nil }) .map({ $0! }) .flatMap(downloadImage) .execute({ img in self.imageView.image = img }) func downloadImage(_ url: URL) -> GAFunction<UIImage?> { return GAFunction(task: { completion in if let image = try? UIImage(data: Data(contentsOf: url)) { completion(image) } else { completion(nil) } }) }
  • 21. Summary 1. 함수는 value 처럼
 - 변수에 담을 수 있다
 - 파라미터로 넘길 수 있다
 - 리턴값으로 반환될 수 있다
 2. 고차함수(Higher-Order Function)
 - 함수가 파라미터로 쓰이거나 반환값으로 사용되는 경우
 - 전달된 함수가 본체의 수행이 종료된 후에 사용되는 경우 @escaping을 해줘야 한다.
 - optional function 은 @escaping이 기본이다.
 3. 함수는 행동을 저장한다
 - 저장한 행동은 전달될 수 있다.
 - 저장된 행동은 나중에 사용될 수 있다.
 4. 이러한 특성들로 여러 재밌는 것들을 만들 수 있다.
 - 사례. GAFunction
 5. 이미 이러한 성질을 이용해서 범용으로 만들어진 라이브러리가 있다.
 - RxSwift 를 쓰자