일급 함수와 고차 함수

minidoo·2021년 4월 29일
0
post-thumbnail

평가

코드가 계산(Evaluation) 되어 값을 만드는 것

일급

  • 값으로 다룰 수 있다.
  • 변수에 담을 수 있다.
  • 함수의 인자로 사용될 수 있다.
  • 함수의 결과로 사용될 수 있다.
const val = 10;
const func = (val) => {
    return 'hello?'
}
func(val);

일급 함수

  • 함수를 값으로 다룰 수 있다.
  • 조합성과 추상화의 도구
const add = a => a + 5;
console.log(add);	// a => a + 5
console.log(add(1));	// 6

const func1 = () => () => 1;
console.log(func1());	// () => 1

const func2 = func1();
console.log(func2);	// () => 1
console.log(func2());	// 1

고차 함수

함수를 값으로 다루는 함수

1. 함수를 인자로 받아서 실행하는 함수

const func1 = func2 => func2(1);
const add = a => a + 1;

console.log(func1(add));		// 2
console.log(func1(a => a + 2));		// 3
const increase = (func, n) => {
    let i = -1;
    while (++i < n) func(i);
}

increase(console.log, 3);			// 0 1 2
increase(a => console.log(a+1), 3)		// 1 2 3

2. 함수를 만들어 리턴하는 함수 (클로저를 만들어 리턴하는 함수)

const add1 = a => b => a + b;
const add2 = add1(10);

console.log(add2);	// b => a(10) + b (a를 기억하고 있음)
console.log(add2(2));	// 12
console.log(add2(3));	// 13

클로저(closure)는 내부함수가 외부함수의 맥락(context)에 접근할 수 있는 것

0개의 댓글