[Functional Programming-Go] First-class function

Jeff Jang·2023년 4월 16일
0
post-thumbnail

위키백과에 써진 정의들을 따라서 Functional Programming에 대한 정의를 하나하나 코딩하면서 작성해보고자 합니다.

첫번째로 나오는 개념은 [First Class and Higher Order Functions] 입니다.(https://en.wikipedia.org/wiki/Functional_programming#First-class_and_higher-order_functions)

이 포스트에서는 First Class Function에 대해서 다루도록 하겠습니다.

영어로 정의된 First-Class Function은 아래와 같고,

while "first-class" is a computer science term for programming language entities that have no restriction on their use (thus first-class functions can appear anywhere in the program that other first-class entities like numbers can, including as arguments to other functions and as their return values).

대략적인 번역은 아래와 같습니다.

일급 함수는 숫자처럼 제한이 없이 사용할 수 있는 함수로, 다른 함수의 인수 혹은 반환값으로 사용가능한 함수.

간단하게 위 개념들을 구현하면 아래와 같습니다. (영어 Comment 참조)

package main
import  (
"fmt"
)
// Define Function type for convenience
type Str2Str func(string) string

func hello(name string) string{ //1st First-Class Func
    return fmt.Sprintf("Hello %s", name)
}
func hola(name string) string{ //2nd First-Class Func
    return fmt.Sprintf("Hola %s", name)
}
func greeting(A Str2Str, B Str2Str) { // General function having functions as Args
   fmt.Println(A("Dog"),B("CatCity"))
}
//This function will get first-class-function by using function name(string) 
func getFunc(fName string) Str2Str {
    var fVar Str2Str
    if (fName == "hello") {
        fVar = hello
    }else if (fName=="hola") {
        fVar = hola
    }else{
        panicMsg := fmt.Sprint("Error - Unexpected Function name : %s", fName)
        panic(panicMsg)
    }
    return fVar
}
// Proceed functions having same signiture using same argument.
func proceedMultipleFunc(str string , funcs...Str2Str ){
    fmt.Println("Start proceed multiple")
    for i,f := range(funcs) {
           fmt.Println(i,f(str))
    }
}

func main(){
    funcHello:= hello
    funcHola:= hola
    //Glimpse of variables
    fmt.Printf("Hello, Value %v ,Type %T\n", funcHello, funcHello)
    fmt.Printf("Hola , Value %v ,Type %T\n", funcHola, funcHola)

    //Let's assign values and Invoke
    hStr:= funcHello("American")
    iStr:= funcHola("Maxican")
    fmt.Println(hStr,iStr)
    //Let's call Another function which has first-class functions as args
    greeting(funcHello,funcHola)

    //getFunc get function using string
    gotFunc := getFunc("hello")
    gotFunc("John")
    gotFunc = getFunc("hola")
    gotFunc("Amigo")

    //Invoke Similar functions by using same argument
    proceedMultipleFunc("Jeff",funcHello,funcHola)
}

Explanation

hello, hola : 일급함수
Str2Str : 편의를 위한 Function에 대한 type 정의
greeting : 일급함수를 인수로 가지는 일반적인 함수
getFunc : String 값에 따라 일급함수를 Return하는 함수
proceeedMultipleFunc : 같은 모양(Signiture)의 함수들을 모두 부르는 함수

Output
Hello, Value 0x482aa0 ,Type func(string) string
Hola , Value 0x482b20 ,Type func(string) string
Hello American Hola Maxican
Hello Dog Hola CatCity
Start proceed multiple
0 Hello Jeff
1 Hola Jeff

다음 Post에서는 Higher Order Function의 개념과 Function Pointer의 차이점에 대해서 알아보도록 하겠습니다.

profile
Software Plumber

0개의 댓글