PHpullh

LANGUAGE COMPARISON

Lambda를 언어별로 비교하기

같은 개념을 실제 예제로 나란히 확인하고, 각 언어의 개별 설명으로 이어갈 수 있습니다.

Kotlin

람다 & 고차함수

함수를 일급 객체로 다루는 Kotlin의 함수형 프로그래밍 핵심.

// 함수 타입
val double: (Int) -> Int = { n -> n * 2 }
val greet: (String) -> String = { "Hello, $it!" }  // it: 단일 파라미터
val add: (Int, Int) -> Int = { a, b -> a + b }

// 고차함수 — 함수를 파라미터로 받기
fun transform(list: List<Int>, fn: (Int) -> Int) =
    list.map(fn)

// 고차함수 — 함수를 반환하기
fun multiplier(factor: Int): (Int) -> Int = { it * factor }

// 함수 합성
infix fun <A, B, C> ((A) -> B).then(g: (B) -> C): (A) -> C =
    { g(this(it)) }

// 메서드 참조
fun isPositive(n: Int) = n > 0
val nums = listOf(-3, -1, 0, 2, 5)
val pos = nums.filter(::isPositive)
val strs = nums.map(Int::toString)

fun main() {
    println(transform(listOf(1,2,3), double))   // [2, 4, 6]
    println(transform(listOf(1,2,3)) { it * it }) // trailing lambda

    val triple = multiplier(3)
    println(triple(7))   // 21

    val process = double then { it + 1 } then { "$it!" }
    println(process(5))  // "11!"
}

Java

람다 & 함수형 인터페이스

Java 8의 람다 표현식과 java.util.function 패키지의 함수형 인터페이스를 마스터합니다.

import java.util.function.*;

public class Lambdas {
    public static void main(String[] args) {
        // 기본 람다
        Runnable r = () -> System.out.println("실행!");
        r.run();

        // Function<T, R> — T 입력, R 출력
        Function<String, Integer> strLen = String::length;
        Function<Integer, Integer> double_ = n -> n * 2;
        Function<String, Integer> composed = strLen.andThen(double_);
        System.out.println(composed.apply("Hello")); // 10

        // Predicate<T> — boolean 반환
        Predicate<String> notEmpty = s -> !s.isEmpty();
        Predicate<String> longStr  = s -> s.length() > 5;
        Predicate<String> both     = notEmpty.and(longStr);
        System.out.println(both.test("Hello World")); // true

        // Consumer<T> — 반환 없음
        Consumer<String> print = System.out::println;
        Consumer<String> printUpper = s -> System.out.println(s.toUpperCase());
        print.andThen(printUpper).accept("java");

        // Supplier<T> — 인자 없음
        Supplier<String> greeting = () -> "Hello, Java!";
        System.out.println(greeting.get());

        // BiFunction<T, U, R>
        BiFunction<Integer, Integer, Integer> add = Integer::sum;
        System.out.println(add.apply(3, 4)); // 7

        // UnaryOperator, BinaryOperator
        UnaryOperator<Integer>   square = n -> n * n;
        BinaryOperator<Integer> multiply = (a, b) -> a * b;
        System.out.println(square.apply(5));    // 25
        System.out.println(multiply.apply(3,4)); // 12
    }
}

PHP

화살표 함수 사용

짧은 변환 로직을 fn 화살표 함수로 표현하는 예제입니다.

<?php
$numbers = [1, 2, 3];
$doubled = array_map(fn (int $n): int => $n * 2, $numbers);

print_r($doubled);