pure function and rx
TRANSCRIPT
Pure Function and Rx
고형호
(Reactive Extensions)
04/10/2016
http://www.slideshare.net/HyungHoKo
1. 코드 시각화
2. 순수 함수
3. 과제
4. 순수 함수로 과제 해결하기
5. 참고 자료
1. 코드 시각화
F1 F2 F3int int int string
F0
F3( );F2( )F1(input) F3(
);F2(
)F1(input)
Left-to-Right
Right-to-Left
Right-to-Left
Botto
m-to
-Topint r1 = F1(input);
int r2 = F2(r1);
string r3 = F3(r2);
?
input
코드시각화
해결
적용추상화
설계 구현
글 쓰기돌파방향
단일 책임
1. Left-to-Right
2. To
p-to
-Botto
m
http://www.yes24.com/24/viewer/preview/17568694
F1 F2 F3int int int string
F0
Left-to-Right
F1(input)
.Pipe(F2)
.Pipe(F3);
Left-to-Right Top
-to-B
otto
mPipe
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 F3int int int string
F0
F1(input).Pipe(F2).Pipe(F3);
F1(input)
.Pipe(F2)
.Pipe(F3);
Left-to-Right Top
-to-B
otto
m
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
4. 순수 함수로 과제 해결하기
F1(input).Do(Log).Pipe(F2).Pipe(F3);
F1 F2 F3int int string
F0
inputint
Logint
F1(input)
.Do(Log)
.Pipe(F2)
.Pipe(F3);
Left-to-Right Top
-to-B
otto
m
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/함수형_프로그래밍
위키백과 - 한글