SlideShare a Scribd company logo
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/함수형_프로그래밍
위키백과 - 한글

More Related Content

PDF
Pure Function and Honest Design
PDF
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...
PDF
[C++ Korea] Effective Modern C++ Study, Item 1 - 3
PPTX
C++ 타입 추론
PDF
Ch05
PDF
Ch07
PDF
Ch10
PDF
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
Pure Function and Honest Design
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...
[C++ Korea] Effective Modern C++ Study, Item 1 - 3
C++ 타입 추론
Ch05
Ch07
Ch10
[C++ Korea] Effective Modern C++ Study item14 16 +신촌

What's hot (20)

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

Similar to Pure Function and Rx (20)

PDF
About Functional Programming Paradigms
PDF
Haskell study 5
PPTX
하스켈 프로그래밍 입문
PDF
키트웍스_발표자료_김경수functional_programming240920.pdf
PDF
자료구조 그래프 보고서
PDF
Scala syntax function
PPTX
하스켈 프로그래밍 입문 2
PPTX
Clean code(03)
PPTX
Startup JavaScript 6 - 함수, 스코프, 클로저
PDF
R 기초 : R Basics
PDF
Haskell study 13
PDF
자료구조 05 최종 보고서
PPTX
Feel functional
PDF
02장 자료형과 연산자
PPTX
Functional programming
DOCX
이산치수학 Project5
PDF
2012 Ds B2 02 Pdf
PDF
2012 Ds B2 02
PPTX
Gpg gems1 1.3
PPTX
튜터링 #10 20120416
About Functional Programming Paradigms
Haskell study 5
하스켈 프로그래밍 입문
키트웍스_발표자료_김경수functional_programming240920.pdf
자료구조 그래프 보고서
Scala syntax function
하스켈 프로그래밍 입문 2
Clean code(03)
Startup JavaScript 6 - 함수, 스코프, 클로저
R 기초 : R Basics
Haskell study 13
자료구조 05 최종 보고서
Feel functional
02장 자료형과 연산자
Functional programming
이산치수학 Project5
2012 Ds B2 02 Pdf
2012 Ds B2 02
Gpg gems1 1.3
튜터링 #10 20120416
Ad

Pure Function and Rx