Skip to content

Latest commit

 

History

History
51 lines (36 loc) · 1.58 KB

02.functional_programming.md

File metadata and controls

51 lines (36 loc) · 1.58 KB

함수형 프로그래밍 소개

img

명령형(Imperative) 프로그래밍

우리가 평소에 사용하던 프로그래밍 패러다임으로, 어떻게 문제를 해결할지에 집중한다.

상태를 수정해서 문제를 해결한다.

예제는 다음과 같다.

public class Test {
    public static void main(String[] args) {
        List<String> animals = Arrays.asList("dog", "cat", "fox");		// step 1
        int dogCount = 0;											// step 2
        
        for(String animal : animal) {								 // step 3
            if(animal.equals("dog")) {								 // step 4
                dogCount ++;
            }
        }
        System.out.println(dogCount);								 // step 5
    }
}

위와 같이 for문을 돌려가며, dogCount 라는 변수의 값을 수정하며 해결하는걸 명령형 프로그래밍 이라고 생각하면 된다.

함수형 프로그래밍

최대한 상태의 변화를 피하고 불변으로 만들어서 문제를 해결하는 프로그래밍 기법이다.

다음 예제로 비교해보자

public class Test {
    public static void main(String[] args) {
        List<String> animals = Arrays.asList("dog", "cat", "fox");
        
        System.out.println(animals.stream()
            .filter(animal -> animal.equals("dog"))
            .collect(Collectors.toList())
            .size());
    }
}

다음과 같이 함수형 프로그램은 부수효과가 없고, 함수형 이기 때문에 Thread-Safe하다