💻 Programming

Functional Programming

Functional Programming

A paradigm emphasizing pure functions and immutability. Minimizes side effects.

📖 Detailed Explanation

Functional Programming is a programming paradigm based on the concept of mathematical functions, with pure functions and immutable data as its core principles. Originating in Lisp, developed by John McCarthy in the 1950s, it is now widely used in languages such as Haskell, Scala, and Clojure, as well as in the functional features of JavaScript and Python.

A pure function is a function that always returns the same output for the same input and does not modify external state. Thanks to this referential transparency, code becomes more predictable, testing and debugging become easier, and it operates safely in parallel processing.

Core concepts of functional programming include first-class functions, higher-order functions, closures, currying, and composition. By using higher-order functions such as map, filter, and reduce, data transformations can be expressed declaratively without loops, making the code concise and its intent clear.

In practice, functional programming is widely applied in React state management (Redux), reactive programming with RxJS, and data pipeline processing. In the AI/ML field in particular, functional patterns are essential for building data preprocessing and transformation pipelines, and side-effect-free code greatly increases stability in microservices and distributed systems.

💻 Code Example

// 1. 순수 함수 vs 비순수 함수
// ❌ 비순수 함수: 외부 상태 의존 및 변경
let discount = 0.1;
function getPrice(price) {
    return price * (1 - discount); // 외부 변수 의존
}

// ✅ 순수 함수: 입력만으로 결과 결정
const getPurePrice = (price, discountRate) => price * (1 - discountRate);

// 2. 불변성 유지 (Immutability)
const user = { name: '김철수', age: 30 };

// ❌ 객체 직접 수정
// user.age = 31;

// ✅ 새 객체 생성 (스프레드 연산자)
const updatedUser = { ...user, age: 31 };
console.log(user);        // { name: '김철수', age: 30 }
console.log(updatedUser); // { name: '김철수', age: 31 }

// 3. 고차 함수 활용 (map, filter, reduce)
const products = [
    { name: '노트북', price: 1200000, category: '전자' },
    { name: '책상', price: 300000, category: '가구' },
    { name: '모니터', price: 400000, category: '전자' },
    { name: '의자', price: 250000, category: '가구' }
];

// 전자 제품만 필터링 후 10% 할인 적용
const discountedElectronics = products
    .filter(p => p.category === '전자')
    .map(p => ({
        ...p,
        price: p.price * 0.9,
        discounted: true
    }));

// 총 가격 계산
const totalPrice = discountedElectronics
    .reduce((sum, p) => sum + p.price, 0);

console.log(`할인된 전자제품 총액: ${totalPrice.toLocaleString()}원`);

// 4. 함수 합성 (Function Composition)
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);

const trim = str => str.trim();
const toLowerCase = str => str.toLowerCase();
const replaceSpaces = str => str.replace(/\s+/g, '-');

// 슬러그 생성 파이프라인
const createSlug = pipe(trim, toLowerCase, replaceSpaces);
console.log(createSlug('  Hello World  ')); // 'hello-world'

// 5. 커링 (Currying)
const multiply = a => b => a * b;
const double = multiply(2);
const triple = multiply(3);

console.log(double(5));  // 10
console.log(triple(5));  // 15

// 실용적 커링 예제: API 요청 빌더
const createRequest = baseUrl => endpoint => params =>
    fetch(`${baseUrl}${endpoint}?${new URLSearchParams(params)}`);

const apiRequest = createRequest('https://api.example.com');
const usersApi = apiRequest('/users');
// usersApi({ page: 1, limit: 10 });

🗣️ Say It Like This in Practice

💬 In a Meeting
"I think we should implement this data pipeline in a functional style. Chaining map and filter lets us express each transformation step clearly, and writing it with pure functions makes unit testing easier and makes it simpler to switch to parallel processing later."
💬 In an Interview
"The core of functional programming is pure functions and immutability. A pure function always returns the same output for the same input and has no side effects, so it is easy to test and can prevent race conditions in concurrent programming. This is also why Redux emphasizes immutability."
💬 In a code review
"What if we replaced this for loop with reduce? The current code mutates an external variable, which causes side effects, but using reduce lets us get the same result more declaratively while maintaining immutability."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Directly modifying arrays/objects

push, pop, splice, and directly assigning object properties modify the original. Use methods that return a new array/object, such as the spread operator, concat, filter, and map. The Immer library also helps with managing immutability.

❌
Referencing/modifying external variables inside a function

Depending on global variables or external state captured by closures means the function is not pure. Take all the values you need as arguments and return only the result. If side effects are necessary, separate them explicitly.

❌
Performance degradation from excessive chaining

Chaining such as map().filter().map() has good readability, but it iterates over a large array multiple times. Consider single-pass processing with the transducer pattern or reduce.

✅
Adopting functional programming gradually

You don't need to convert all your code to functional style at once. Start with data transformation logic, separate it into pure functions, and apply it gradually by managing side effects at the boundaries.

🔗 Related Terms

📚 Learn More