pure function and rx

41
Pure Function and Rx 고형호 [email protected] (Reactive Extensions) 04/10/2016 http://www.slideshare.net/HyungHoKo

Upload: hyungho-ko

Post on 18-Jan-2017

978 views

Category:

Software


3 download

TRANSCRIPT

Page 1: Pure Function and Rx

Pure Function and Rx

고형호

[email protected]

(Reactive Extensions)

04/10/2016

http://www.slideshare.net/HyungHoKo

Page 2: Pure Function and Rx

1. 코드 시각화

2. 순수 함수

3. 과제

4. 순수 함수로 과제 해결하기

5. 참고 자료

Page 3: Pure Function and Rx

1. 코드 시각화

Page 4: Pure Function and Rx

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

Page 5: Pure Function and Rx

코드시각화

해결

적용추상화

설계 구현

글 쓰기돌파방향

단일 책임

Page 6: Pure Function and Rx

1. Left-to-Right

2. To

p-to

-Botto

m

http://www.yes24.com/24/viewer/preview/17568694

Page 7: Pure Function and Rx

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);

Page 8: Pure Function and Rx

순수 함수는 블랙박스다.

일관성(참조 투명성)

부수 효과 Free

입력 출력함수부수 효과(Side Effect)

변경

외부 데이터

변경 참조

비순수 함수

호출

입력 값만으로 출력 값이 결정된다.

블랙박스

입력 인수를 전달하여

출력 결과를 반환한다.

함수 내부관심

입력과 출력에만 집중한다.

Declarative Programming

Page 9: Pure Function and Rx

2. 순수 함수

Page 10: Pure Function and Rx

int Divide(int x, int y){

return x / y;}

DivideByZeroException

How?

Page 11: Pure Function and Rx

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;}

?

Page 12: Pure Function and Rx

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 값이 변하지 않는다면,

Page 13: Pure Function and Rx

x 값이 변하지 않는다면,

ReferentiallyTransparent(x) ReferentiallyTransparent(x) 항상

같은 결과 값

같은인자 값

ReferentiallyTransparent(6) ReferentiallyTransparent(6) 7

ReferentiallyTransparent(5) ReferentiallyTransparent(4 + 1) 6

int ReferentiallyTransparent(int x)

{

return x + 1;

}

Page 14: Pure Function and Rx

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;

}

Page 15: Pure Function and Rx

The function

always evaluates

the same result value

given the same argument value(s).

ReferentiallyTransparent(x) ReferentiallyTransparent(x)

x 값이 변하지 않는다면,

참조 투명성(일관성)을 갖는다.(Referential Transparency)

Page 16: Pure Function and Rx

외부데이터 변경

참조

타입 비순수 함수(매개 변수, …)

{

return …;}

변경

외부비순수 함수

호출

int ReferentiallyTransparent(int x)

{

return x + 1;

}

int globalValue = 0;

int ReferentiallyOpaque(int x)

{globalValue += 1;

return x + globalValue;

}

부수 효과(Side Effect)

함수의 실행이

외부에 영향을 끼치거나 참조하는 것.

Page 17: Pure Function and Rx

전역적 추론(Reasoning)이 필요하다.

미루어 생각하여 논함

코드를 이해하기 위해서

타입 비순수 함수(매개 변수, …)

{

return …;}

외부데이터

외부비순수 함수

변경

호출변경

참조

부수 효과(Side Effect)

Page 18: Pure Function and Rx

외부데이터 변경

참조

타입 순수 함수(매개 변수, …)

{

return …;}

int ReferentiallyTransparent(int x)

{

return x + 1;

}

int globalValue = 0;

int ReferentiallyOpaque(int x)

{globalValue += 1;

return x + globalValue;

}

변경

외부비순수 함수

호출부수 효과

(Side Effect)

Page 19: Pure Function and Rx

결과만

타입 순수 함수(매개 변수, …)

{

return …;}

int ReferentiallyTransparent(int x)

{

return x + 1;

}

int globalValue = 0;

int ReferentiallyOpaque(int x)

{globalValue += 1;

return x + globalValue;

}

외부순수 함수

호출부수 효과

(Side Effect)

참조

Page 20: Pure Function and Rx

결과만

지역적 추론(Reasoning)만 필요하다.

미루어 생각하여 논함

코드를 이해하기 위해서

타입 순수 함수(매개 변수, …)

{

return …;}

외부순수 함수

호출부수 효과

(Side Effect)

참조

Page 21: Pure Function and Rx

결과만

Evaluation of the result

does not cause

any semantically observable side effect.

타입 순수 함수(매개 변수, …)

{

return …;}

외부순수 함수

호출부수 효과

(Side Effect)

참조

부수 효과가 없다.

(Side Effects)

Page 22: Pure Function and Rx

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 …

Page 23: Pure Function and Rx

입력 출력함수입력 값만으로

부수 효과(Side Effect) 출력 값이 결정된다.

함수

외부

함수

외부

관심(입력을 어떻게 얻을 것인가?)

관심(결과로 무엇을 할 것인가?)

입력과 출력에만 집중한다.

Declarative Programming

Page 24: Pure Function and Rx

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;

}

Page 25: Pure Function and Rx

3. 과제

Page 26: Pure Function and Rx

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

로그는?

Page 27: Pure Function and Rx

1에서 N까지 제곱(Square) 합 구하기

int result = 0;

for (int i = 1; i <= N; i++)

{

result += Square(i);}

int Square(int i)

{

return i * i;

}

Page 28: Pure Function and Rx

마우스 이벤트 등록

마우스 위치 데이터

개수(3개) 확인

마우스 위치 추가

그리기 객체생성 및 추가

마우스 위치 데이터 삭제

마우스 위치 데이터 Buffer

Page 29: Pure Function and Rx

사용자

비밀번호

로그인 취소

이메일 형식([email protected])

4개 이상 문자

배경 색상 변경

배경 색상 변경

모두 만족할 때

활성화

Page 30: Pure Function and Rx

4. 순수 함수로 과제 해결하기

Page 31: Pure Function and Rx

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

Page 32: Pure Function and Rx

1에서 N까지 제곱(Square) 합 구하기

제곱1 … NVs. 합

Page 33: Pure Function and Rx

제곱 합1 … N

Enumerable.Range(1, 3)

.Select(Square)

.Sum();

Enumerable.Range(1, 3)

.Select(Square)

.Sum();

.Do(Log)

.Do(Log)

로그 로그제곱1 … N 합

Page 34: Pure Function and Rx

_canvas

FromEventPattern(TextChanged)

이벤트

Select(GetPosition)

마우스 위치

Select(new Polygon)

그리기 객체

Subscribe(Add)

그리기

Buffer(3)

연속 데이터

Page 35: Pure Function and Rx

_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));

Page 36: Pure Function and Rx

Select(object string)

타입 변경

Select(object string)

타입 변경

FromEventPattern(TextChanged)

이벤트

FromEventPattern(TextChanged)

이벤트

색상

Subscribe

색상

Subscribe

활성화

Subscribe

CombineLatest

textBoxPW 조건

Select(Length > 3)

textBoxID 조건

Select(Regex.Match)

Page 37: Pure Function and Rx

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;});

Page 38: Pure Function and Rx

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;});

Page 39: Pure Function and Rx

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;});

Page 40: Pure Function and Rx

5. 참고 자료

Page 41: Pure Function and Rx

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/함수형_프로그래밍

위키백과 - 한글