LandvibeDev / study-repo

스터디 repository 모음
0 stars 0 forks source link

[모던 자바 인 액션] 10주차 #12

Open jeongminkyo opened 1 year ago

jeongminkyo commented 1 year ago

스터디 날짜 2023.09.01 금 9:00-10:00

내용 챕터19. 함수형 프로그래밍 기법 챕터20. OOP와 FP의 조화: 자바와 스칼라의 비교 챕터21. 결론 그리고 자바의 미래

공유

최승위

이성온

정민교

jeongminkyo commented 1 year ago

자바 8의 기능 리뷰

변화가 생긴 이유

동작 파라미터화(람다와 메서드 참조)

apple -> apple.getWeight() > 150 // 람다 코드를 전달할 수 있다.
Apple::isHeavy // 기존 메서드의 메서드 참조를 전달할 수 있다.

스트림

기존 컬렉션에 filter, map 등의 메서드를 추가하지 않고 스트림을 만든 이유

CompletableFuture 클래스

Optional 클래스

Flow API

디폴트 메서드

so3500 commented 1 year ago

일급 함수 (fist-class function)

Function<String, Integer> strToInt = Integer::parseInt;

고차원 함수 (high-order function)

Comparator<Apple> c = compainrg(Apple::getWeight);

커링 (currying)

예시) 섭씨를 화씨로 변환

// 섭씨를 화씨로 변환하는 예시 CtoF(x) = x*9/5 + 32
static double converter(double x, double f, double b) {
    return x * f + b;
}

double fTem = converter(30, 9/5, 32);
double krw = converter(1000, 1325, 0);

예시) 개선된 변환코드

static DoubleUnaryOperator curriedConverter(double f, double b) {
    return (double x) -> x * f + b;
}

// 사용예시
DoubleUnaryOperator convertCtoF = curriedConverter(9/5, 32);
double fTem = convertCtoF.applyAsDouble(30);

DoubleUnaryOperator convertUSDtoKRW = curriedConverter(1325, 0);
double krw = convertUSDtoKRW.applyAsDouble(1000);

영속 자료구조 (persistent data structure)

파괴적인 갱신과 함수형

// A에서 B까지 기차여행을 의미해는 가변 클래스
// 단방향 연결 리스트로 구현
class TrainJourney {
    public int price;
    public TrainJourney onward;
    public TrainJourney(int p, TrainJourney t) {
        price = p;
        onward = t;
    }
}

image

// 자료구조가 파괴적으로 갱신됨
static TrainJourney link(TrainJourney a, TrainJourney b) {
    if (a == null) return b;
    TrainJourney t = a;
    while(t.onward != null) {
        t = t.onward;
    }
    t.onward = b;
    return a;
}
// 자료구조가 갱신되지 않음
static TrainJourney append(TrainJourney a, TrainJourney b) {
    return a == null ? b : new TrainJourney(a.price, append(a.onward, b));
}

image

패턴 매칭

def simplifyExpression(expr: Expr): Expr = expr match {
    case BinOp("+", e, Number(0)) => e  // 0 더하기
    case BinOp("*", e, Number(1)) => e  // 1 곱하기
    case BinOp("/", e, Number(1)) => e  // 1 나누기
    case _ => expr                      // expr을 단순화할 수 없다
}
// ASIS
if (obj instanceof String) {
    String t = (String) obj;
}

// TOBE
if (obj instanceof String t) {
 t.isEmtpy
}

[JEP 441: Pattern Matching for switch](https://openjdk.org/jeps/441)