SlideShare uma empresa Scribd logo
1 de 41
Baixar para ler offline
Pure Function and Rx
고형호
hyungho.ko@gmail.com
(Reactive Extensions)
04/10/2016
http://www.slideshare.net/HyungHoKo
1. 코드 시각화
2. 순수 함수
3. 과제
4. 순수 함수로 과제 해결하기
5. 참고 자료
1. 코드 시각화
F1 F2 F3
int int int string
F0
F3( );F2( )F1(input) F3(
);
F2(
)F1(input)
Left-to-Right
Right-to-Left
Right-to-Left
Bottom-to-Top
int r1 = F1(input);
int r2 = F2(r1);
string r3 = F3(r2);
?
input
코드
시각화
해결
적용추상화
설계 구현
글 쓰기
돌파
방향
단일 책임
1. Left-to-Right
2.Top-to-Bottom
http://www.yes24.com/24/viewer/preview/17568694
F1 F2 F3
int int int string
F0
Left-to-Right
F1(input)
.Pipe(F2)
.Pipe(F3);
Left-to-Right
Top-to-Bottom
Pipe
input
F1(input).Pipe(F2).Pipe(F3);
순수 함수는 블랙박스다.
일관성(참조 투명성)
부수 효과 Free
입력 출력함수부수 효과
(Side Effect)
변경
외부 데이터
변경 참조
비순수 함수
호출
입력 값만으로 출력 값이 결정된다.
블랙박스
입력 인수를 전달하여
출력 결과를 반환한다.
함수 내부
관심
입력과 출력에만 집중한다.
Declarative Programming
2. 순수 함수
int Divide(int x, int y)
{
return x / y;
}
DivideByZeroException
How?
int Divide(int x, int y)
{
try
{
return x / y;
}
catch (DivideByZeroException excep)
{
…
}
return ?
}
?
bool TryDivide(int x, int y, out int result)
{
try
{
result = x / y;
}
catch (DivideByZeroException excep)
{
result = ?
return false;
}
return true;
}
?
int Divide(int x, int y)
{
if (y == 0)
throw new DivideByZeroException
return x / y;
}
?
int ReferentiallyTransparent(int x)
{
return x + 1;
}
int globalValue = 0;
int ReferentiallyOpaque(int x)
{
globalValue += 1;
return x + globalValue;
}
ReferentiallyTransparent(x) ReferentiallyTransparent(x)
ReferentiallyOpaque(x) ReferentiallyOpaque(x)
x 값이 변하지 않는다면,
x 값이 변하지 않는다면,
ReferentiallyTransparent(x) ReferentiallyTransparent(x)
항상
같은 결과 값
같은
인자 값
ReferentiallyTransparent(6) ReferentiallyTransparent(6) 7
ReferentiallyTransparent(5) ReferentiallyTransparent(4 + 1) 6
int ReferentiallyTransparent(int x)
{
return x + 1;
}
x 값이 변하지 않는다면,
ReferentiallyOpaque(6) ReferentiallyOpaque(6) 7
ReferentiallyOpaque(5) ReferentiallyOpaque(4 + 1) 6
항상
같은 결과 값
같은
인자 값
ReferentiallyOpaque(x) ReferentiallyOpaque(x)
int globalValue = 0;
int ReferentiallyOpaque(int x)
{
globalValue += 1;
return x + globalValue;
}
The function
always evaluates
the same result value
given the same argument value(s).
ReferentiallyTransparent(x) ReferentiallyTransparent(x)
x 값이 변하지 않는다면,
참조 투명성(일관성)을 갖는다.
(Referential Transparency)
외부
데이터 변경
참조
타입 비순수 함수(매개 변수, …)
{
…
return …;
}
변경
외부
비순수 함수
호출
int ReferentiallyTransparent(int x)
{
return x + 1;
}
int globalValue = 0;
int ReferentiallyOpaque(int x)
{
globalValue += 1;
return x + globalValue;
}
부수 효과
(Side Effect)
함수의 실행이
외부에 영향을 끼치거나 참조하는 것.
전역적 추론(Reasoning)이 필요하다.
미루어 생각하여 논함
코드를 이해하기 위해서
타입 비순수 함수(매개 변수, …)
{
…
return …;
}
외부
데이터
외부
비순수 함수
변경
호출
변경
참조
부수 효과
(Side Effect)
외부
데이터 변경
참조
타입 순수 함수(매개 변수, …)
{
…
return …;
}
int ReferentiallyTransparent(int x)
{
return x + 1;
}
int globalValue = 0;
int ReferentiallyOpaque(int x)
{
globalValue += 1;
return x + globalValue;
}
변경
외부
비순수 함수
호출
부수 효과
(Side Effect)
결과만
타입 순수 함수(매개 변수, …)
{
…
return …;
}
int ReferentiallyTransparent(int x)
{
return x + 1;
}
int globalValue = 0;
int ReferentiallyOpaque(int x)
{
globalValue += 1;
return x + globalValue;
}
외부
순수 함수
호출
부수 효과
(Side Effect)
참조
결과만
지역적 추론(Reasoning)만 필요하다.
미루어 생각하여 논함
코드를 이해하기 위해서
타입 순수 함수(매개 변수, …)
{
…
return …;
}
외부
순수 함수
호출
부수 효과
(Side Effect)
참조
결과만
Evaluation of the result
does not cause
any semantically observable side effect.
타입 순수 함수(매개 변수, …)
{
…
return …;
}
외부
순수 함수
호출
부수 효과
(Side Effect)
참조
부수 효과가 없다.
(Side Effects)
It has no side effects.
It is consistent.
(Referential Transparency)
This is
a property of expressions in general
and not just functions.
1 + 6
(this is not a function, but this is a expression.)
Pure FunctionMathematical Function …
입력 출력함수
입력 값만으로
부수 효과
(Side Effect) 출력 값이 결정된다.
함수
외부
함수
외부
관심
(입력을 어떻게 얻을 것인가?)
관심
(결과로 무엇을 할 것인가?)
입력과 출력에만 집중한다.
Declarative Programming
int Divide(int x, int y)
{
if (y == 0)
throw new DivideByZeroException
return x / y;
}
int Divide(int x, int y)
{
try
{
return x / y;
}
catch (DivideByZeroException excep)
{
…
}
return ?
}
bool TryDivide(int x, int y, out int result)
{
try
{
result = x / y;
}
catch (DivideByZeroException excep)
{
result = ?
return false;
}
return true;
}
3. 과제
F1 F2 F3
int int int string
F0
F1(input).Pipe(F2).Pipe(F3);
F1(input)
.Pipe(F2)
.Pipe(F3);
Left-to-Right
Top-to-Bottom
Pipe
input
로그는?
1에서 N까지 제곱(Square) 합 구하기
int result = 0;
for (int i = 1; i <= N; i++)
{
result += Square(i);
}
int Square(int i)
{
return i * i;
}
마우스 이벤트 등록
마우스 위치 데이터
개수(3개) 확인
마우스 위치 추가
그리기 객체
생성 및 추가
마우스 위치 데이터 삭제
마우스 위치 데이터 Buffer
사용자
비밀번호
로그인 취소
이메일 형식(hyungho.ko@gmail.com)
4개 이상 문자
배경 색상 변경
배경 색상 변경
모두 만족할 때
활성화
4. 순수 함수로 과제 해결하기
F1(input).Do(Log).Pipe(F2).Pipe(F3);
F1 F2 F3
int int string
F0
input
int
Log
int
F1(input)
.Do(Log)
.Pipe(F2)
.Pipe(F3);
Left-to-Right
Top-to-Bottom
1에서 N까지 제곱(Square) 합 구하기
제곱1 … NVs. 합
제곱 합1 … N
Enumerable.Range(1, 3)
.Select(Square)
.Sum();
Enumerable.Range(1, 3)
.Select(Square)
.Sum();
.Do(Log)
.Do(Log)
로그 로그제곱1 … N 합
_canvas
FromEventPattern
(TextChanged)
이벤트
Select
(GetPosition)
마우스 위치
Select
(new Polygon)
그리기 객체
Subscribe
(Add)
그리기
Buffer
(3)
연속 데이터
_canvas
FromEventPattern
(TextChanged)
이벤트
Select
(GetPosition)
마우스 위치
Buffer
(3)
연속 데이터
Select
(new Polygon)
그리기 객체
Subscribe
(Add)
그리기
Observable
.FromEventPattern<MouseButtonEventHandler, MouseButtonEventArgs>(
handler => _canvas.MouseLeftButtonDown += handler,
handler => _canvas.MouseLeftButtonDown -= handler)
.Select(e => e.EventArgs.GetPosition(_canvas))
.Buffer(3)
.Select((IList<Point> points) => new Polygon
{
Points = new PointCollection(points),
Stroke = Brushes.Blue,
StrokeThickness = 3
})
.Subscribe(t => _canvas.Children.Add(t));
Select
(object  string)
타입 변경
Select
(object  string)
타입 변경
FromEventPattern
(TextChanged)
이벤트
FromEventPattern
(TextChanged)
이벤트
색상
Subscribe
색상
Subscribe
활성화
Subscribe
CombineLatest
textBoxPW 조건
Select
(Length > 3)
textBoxID 조건
Select
(Regex.Match)
IObservable<bool> idObservable = Observable
.FromEventPattern<EventHandler, EventArgs>(
h => textBoxID.TextChanged += h,
h => textBoxID.TextChanged -= h)
.Select(e => ((TextBox)e.Sender).Text)
.Select(text =>
{
Regex regex = new Regex(@"^([w.-]+)@([w-]+)((.(w){2,3})+)$");
return regex.Match(text).Success;
});
idObservable.Subscribe(result =>
{
if (!result)
textBoxID.BackColor = Color.SkyBlue;
else
textBoxID.BackColor = Color.White;
});
IObservable<bool> pwObservable = Observable
.FromEventPattern<EventHandler, EventArgs>(
h => textBoxPW.TextChanged += h,
h => textBoxPW.TextChanged -= h)
.Select(e => ((TextBox)e.Sender).Text)
.Select(text => text.Length > 3);
pwObservable.Subscribe(result =>
{
if (!result)
textBoxPW.BackColor = Color.SkyBlue;
else
textBoxPW.BackColor = Color.White;
});
combineEnabled.Subscribe(enabled =>
{
if (enabled)
buttonLogin.Enabled = true;
else
buttonLogin.Enabled = false;
});
var combineEnabled = Observable.CombineLatest(idObservable, pwObservable, (enabledID, enabledPW) =>
{
if (enabledID && enabledPW)
return true;
else
return false;
});
5. 참고 자료
https://en.wikipedia.org/wiki/Declarative_programming
위키백과
https://en.wikipedia.org/wiki/Functional_programming
https://en.wikipedia.org/wiki/Pure_function
https://en.wikipedia.org/wiki/Referential_transparency
https://en.wikipedia.org/wiki/Side_effect_(computer_science)
https://channel9.msdn.com/Events/TechDays/TDK2015/T3-6
너에게만 나는 반응해 반응형(Reactive) 응용프로그램 아키텍처
https://ko.wikipedia.org/wiki부작용_(컴퓨터 과학)
https://ko.wikipedia.org/wiki/함수형_프로그래밍
위키백과 - 한글

Mais conteúdo relacionado

Mais procurados

[C++ korea] effective modern c++ study item8~10 정은식
[C++ korea] effective modern c++ study item8~10 정은식[C++ korea] effective modern c++ study item8~10 정은식
[C++ korea] effective modern c++ study item8~10 정은식은식 정
 
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...Seok-joon Yun
 
[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...
[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...
[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...Seok-joon Yun
 
[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...
[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...
[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...Seok-joon Yun
 
[C++ korea] effective modern c++ study item 1정은식
[C++ korea] effective modern c++ study item 1정은식[C++ korea] effective modern c++ study item 1정은식
[C++ korea] effective modern c++ study item 1정은식은식 정
 
[C++ korea] effective modern c++ study item 1 understand template type dedu...
[C++ korea] effective modern c++ study   item 1 understand template type dedu...[C++ korea] effective modern c++ study   item 1 understand template type dedu...
[C++ korea] effective modern c++ study item 1 understand template type dedu...Seok-joon Yun
 
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준Seok-joon Yun
 
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...Seok-joon Yun
 
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...Seok-joon Yun
 
C++17 Key Features Summary - Ver 2
C++17 Key Features Summary - Ver 2C++17 Key Features Summary - Ver 2
C++17 Key Features Summary - Ver 2Chris Ohk
 
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기Chris Ohk
 
Template at c++
Template at c++Template at c++
Template at c++Lusain Kim
 
[C++ Korea] Effective Modern C++ Study item 24-26
[C++ Korea] Effective Modern C++ Study item 24-26[C++ Korea] Effective Modern C++ Study item 24-26
[C++ Korea] Effective Modern C++ Study item 24-26Seok-joon Yun
 
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)코딩인카페 C&JAVA 기초과정 C프로그래밍(3)
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)유익아카데미
 
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23Seok-joon Yun
 
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...Seok-joon Yun
 
코딩인카페 C&JAVA 기초과정 C프로그래밍(2)
코딩인카페 C&JAVA 기초과정 C프로그래밍(2)코딩인카페 C&JAVA 기초과정 C프로그래밍(2)
코딩인카페 C&JAVA 기초과정 C프로그래밍(2)유익아카데미
 

Mais procurados (20)

[C++ korea] effective modern c++ study item8~10 정은식
[C++ korea] effective modern c++ study item8~10 정은식[C++ korea] effective modern c++ study item8~10 정은식
[C++ korea] effective modern c++ study item8~10 정은식
 
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
 
[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...
[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...
[C++ korea] Effective Modern C++ study item 19 use shared ptr for shared owne...
 
[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...
[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...
[C++ korea] effective modern c++ study item 7 distinguish between () and {} w...
 
[C++ korea] effective modern c++ study item 1정은식
[C++ korea] effective modern c++ study item 1정은식[C++ korea] effective modern c++ study item 1정은식
[C++ korea] effective modern c++ study item 1정은식
 
[C++ korea] effective modern c++ study item 1 understand template type dedu...
[C++ korea] effective modern c++ study   item 1 understand template type dedu...[C++ korea] effective modern c++ study   item 1 understand template type dedu...
[C++ korea] effective modern c++ study item 1 understand template type dedu...
 
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
 
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...
 
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
 
Ch11
Ch11Ch11
Ch11
 
C++17 Key Features Summary - Ver 2
C++17 Key Features Summary - Ver 2C++17 Key Features Summary - Ver 2
C++17 Key Features Summary - Ver 2
 
C++11
C++11C++11
C++11
 
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
 
Template at c++
Template at c++Template at c++
Template at c++
 
[C++ Korea] Effective Modern C++ Study item 24-26
[C++ Korea] Effective Modern C++ Study item 24-26[C++ Korea] Effective Modern C++ Study item 24-26
[C++ Korea] Effective Modern C++ Study item 24-26
 
Ch08
Ch08Ch08
Ch08
 
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)코딩인카페 C&JAVA 기초과정 C프로그래밍(3)
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)
 
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
 
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
 
코딩인카페 C&JAVA 기초과정 C프로그래밍(2)
코딩인카페 C&JAVA 기초과정 C프로그래밍(2)코딩인카페 C&JAVA 기초과정 C프로그래밍(2)
코딩인카페 C&JAVA 기초과정 C프로그래밍(2)
 

Semelhante a Pure Function and Rx

피보나치 수열과 파이썬.pptx
피보나치 수열과 파이썬.pptx피보나치 수열과 파이썬.pptx
피보나치 수열과 파이썬.pptxssuser791410
 
알고리즘과 자료구조
알고리즘과 자료구조알고리즘과 자료구조
알고리즘과 자료구조영기 김
 
4. 함수포인터
4. 함수포인터4. 함수포인터
4. 함수포인터Hoyoung Jung
 
Function & Closure about Swift
Function & Closure about Swift Function & Closure about Swift
Function & Closure about Swift KimDaeho
 
C언어 세미나 - 함수
C언어 세미나 - 함수C언어 세미나 - 함수
C언어 세미나 - 함수SeungHyun Lee
 
포인터의기초 (2) - 포인터 사용하기1
포인터의기초 (2) - 포인터 사용하기1포인터의기초 (2) - 포인터 사용하기1
포인터의기초 (2) - 포인터 사용하기1Hoyoung Jung
 
이산수학 C1 프로젝트 3
이산수학 C1 프로젝트 3이산수학 C1 프로젝트 3
이산수학 C1 프로젝트 3pkok15
 
[Swift] Functions
[Swift] Functions[Swift] Functions
[Swift] FunctionsBill Kim
 

Semelhante a Pure Function and Rx (12)

피보나치 수열과 파이썬.pptx
피보나치 수열과 파이썬.pptx피보나치 수열과 파이썬.pptx
피보나치 수열과 파이썬.pptx
 
3.포인터
3.포인터3.포인터
3.포인터
 
알고리즘과 자료구조
알고리즘과 자료구조알고리즘과 자료구조
알고리즘과 자료구조
 
4. 함수포인터
4. 함수포인터4. 함수포인터
4. 함수포인터
 
Function & Closure about Swift
Function & Closure about Swift Function & Closure about Swift
Function & Closure about Swift
 
이산수학03
이산수학03이산수학03
이산수학03
 
C언어 세미나 - 함수
C언어 세미나 - 함수C언어 세미나 - 함수
C언어 세미나 - 함수
 
Fp basic-kotlin
Fp basic-kotlinFp basic-kotlin
Fp basic-kotlin
 
포인터의기초 (2) - 포인터 사용하기1
포인터의기초 (2) - 포인터 사용하기1포인터의기초 (2) - 포인터 사용하기1
포인터의기초 (2) - 포인터 사용하기1
 
이산수학 C1 프로젝트 3
이산수학 C1 프로젝트 3이산수학 C1 프로젝트 3
이산수학 C1 프로젝트 3
 
[Swift] Functions
[Swift] Functions[Swift] Functions
[Swift] Functions
 
Go
GoGo
Go
 

Pure Function and Rx