2023-10-15
- 함수형 프로그래밍 관련 코드 적용해보기
- scope closure curry
- lazy evaluation
- function composition
---
# scope closure
### scope(스코프, 유효 범위)
- 변수에 접근할 수 있는 범위
- 함수 안에 함수가 있을 때 내부 함수에서 외부 함수에 있는 변수에 접근이 가능하다(lexical scope) -> 반대(외부 함수에서 내부 함수로의 접근)는 불가능
- 이 때 외부 함수의 변수는 선언 당시 값에서 바뀔 수 없기 때문에 final로 선언되어 있지 않더라도 암묵적으로 final 취급 -> 내부 함수에서 바꾸려고 하면 compile error
### curry
- 여러 개의 매개변수를 받는 함수를 중첩된 여러 개의 함수로 쪼개서 한번에 받지 않고 여러 단계로 결쳐 나눠 받게 하는 기술
```java
BiFunction<Integer, Integer, Integer> add = (x, y) -> x + y;
Function<Integer, Function<Integer, Integer>> curried = x -> y -> x + y;
Function<Integer, Integer> addThree = curried.apply(3);
int result = addThree.apply(10);
System.out.println("result = " + result); // 13
```
# lazy evaluation
- Lambda의 계산은 그 결과값이 필요할 때가 되어서야 한다.
### 장점
- 불필요한 계산을 줄이거나,
- 해당 코드의 실행 순서를 의도적으로 미룰 수 있다.
# Function Composition
- 여러 개의 함수를 합쳐 하나의 새로운 함수를 만드는 것
```java
Predicate<String> startsWithA = (text) -> text.startsWith("A");
Predicate<String> endsWithX = (text) -> text.endsWith("x");
Predicate<String> startsWithAAndEndsWithX =
(text) -> startsWithA.test(text) && endsWithX.test(text);
String input = "A hardworking person must relax";
boolean result = startsWithAAndEndsWithX.test(input);
System.out.println(result); // true
```