First-class functions(Objects)
Programming Language 관련, 혹은 Pattern 관련 글들을 읽다보면 First Class Function(Object 혹은 Element) 이란 단어를 심심치 않게 접하게 된다. 위키피디아의 정의는 아래와 같다.
In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. Specifically, this means the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures.[1] Some programming language theorists require support for anonymous functions(function literals) as well.[2] In languages with first-class functions, the names of functions do not have any special status; they are treated like ordinary variables with a function type.[3] The term was coined by Christopher Strachey in the context of “functions as first-class citizens” in the mid-1960s.[4]
정의를 풀면,
컴퓨터학에서 프로그래밍 언어가 first-class function을 가진다는 말은 function들을 최고 계층 시민(first-class citizen)으로 간주하는 경우를 말한다. 특별히, 언어가 function을 다른 function의 파라미터로 전달할 수 있거나, function의 리턴 값으로 사용할 수 있다거나, 변수에 저장되고, 구조체에 저장될 수 있는 것을 지원하는 경우를 말한다. 몇몇 프로그래밍 언어학자들은 Anonymous Function의 지원까지도 포함되어야 한다고 이야기한다. First-class functions을 지원하는 언어에서는 function의 이름이 특별한 상태를 가지는 것이 아니다. 그냥 함수 타입을 가지는 일반적인 변수일 뿐이다. first-class function이라는 용어는 1960대 중반 “functions as first-class citizens”이라는 문맥에서 Christopher Strachey가 처음 사용했다.
즉,
Programming 언어가 First Class Function의 특성을 가지는 언어라고 하면 Function이 다음의 특성을 가지는 언어를 말한다.
1 2 3 4 5 6 7 8 9 |
변수에 저장 가능하다. 함수의 파라미터로 전달 가능하다. 함수의 리턴값으로 사용 가능하다. 데이터 구조체에 포함될 수 있다. (ObjectType의 Instance 중 하나이다.) (실행 타임에 구성할 수 있다.) (Property를 가질 수 있다.) |
이는 First Class Object, First Class Element도 역시 Function과 대치하면 적용 가능하다. 이러한 특성을 가진 언어에서는 함수를 가지고 거의 모든 일을 할 수 있는 자유도를 가지게 된다. 예를 들면, C에서 function은 first class function이 아닌 반면에, C++에서의 class의 instance는 first class citizen이다.
javascript는 first-class function을 가진 가장 대표적인 언어이다. 그래서 아래와 같이 C에서는 못하는 일들을 할 수있다.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var lion = function(){console.log("grrrrrrrr");} lion.enZooed = false; var lamb = function(){console.log("mehhhhhhhh");} var EnZoo = function(animal){animal(); animal.enZooed = true;} EnZoo(lion); EnZoo(lamb); console.log(lion.enZooed); console.log(lamb.enZooed); |
Output:
1 2 3 4 5 6 |
grrrrrrrr mehhhhhhhh true true |
비교적 최근에 나온 언어인 Haskell 이나 Go도 First Class Function을 모두 지원하며, 이런 First Class Function을 지원하는 언어는 개발시에 Function 타입들에 대해서 유연하게 다룰 수 있다. 그래서 C와 같은 Second Class Function의 언어보다 개발시에 불필요한 복잡도를 없애고 효율적으로 코딩할 수 있는 이점이 있다. C++의 경우에도 C++11에 와서는 Lambda Function을 지원하게 되면서 본격적으로 First Class Function의 특성을 가지는 언어에 합류하게 되었다.