함수형 프로그래밍 기본기

dorazi·2022년 7월 23일
post-thumbnail

평가와 일급

평가

평가라는 용어는 코드가 계산되어 값을 만드는 것을 의미한다.

1 + 1 // 2
(1 + 2) + 3 // 6

일급

  • 값으로 다룰 수 있다.
  • 변수에 담을 수 있다.
  • 함수의 인자로 사용될 수 있다.
  • 함수의 결과로 사용될 수 있다.
const a = 10;
const add10 = a => a + 10;
const r = add10(a);
console.log(r) // 20

일급 함수

자바스크립트에서 함수는 일급이다.

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

const f1 = () => () => 1;
console.log(f1());

const f2 = f1();
log(f2); // () => 1
log(f2()); // 1

고차 함수

  • 함수를 값으로 다루는 함수
const apply1 = f => f(1);
const add2 = a => a + 2;
console.log(apply1(add2)) // 3
console.log(a => a - 1) // 0

const times = (f, n) => {
  let i = -1;
  while (++1 < n) f(i);
}

times(console.log, 3);

times(a => log(a + 10), 3);
  • 함수를 만들어 리턴하는 함수 (클로저를 만들어 리턴하는 함수)
  • addMaker
const addMaker = a => b => a + b;
const add10 = addMaker(10); // b => a + b
console.log(add10(5)); // 15
  • add10 에서 넘겨준 10을 기억하고 있어서 15라는 결과가 나온다
profile
프론트엔드 개발자

0개의 댓글