일급 함수 및 고차 함수
함수를 값으로 다루는 방법과 함수를 전달하고 강력한 고차 함수를 만드는 방법을 이해합니다.
일급 함수 및 고차 함수은(는) CoddyKit의 무료 Clojure Functional Programming & JVM Backend Development 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Clojure Functional Programming & JVM Backend Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Clojure Functional Programming & JVM Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Functions: First-Class Citizens
In Clojure, functions are "first-class citizens." This means they are treated just like any other value, such as numbers or strings.
You can:
- Assign them to variables.
- Pass them as arguments to other functions.
- Return them as results from other functions.
This powerful concept is fundamental to functional programming!
Assigning Functions to Names
Let's see how we can treat functions as values by assigning them to a name using def or let. Think of it as giving a nickname to a function.
Try running this example:
(ns coddykit.core
(:gen-class))
(defn greet [name]
(str "Hello, " name "!"))
(defn -main [& args]
(println "--- Output ---")
(def my-greeting greet) ; Assign 'greet' function to 'my-greeting'
(println (my-greeting "Alice")))Passing Functions as Arguments
A key aspect of first-class functions is the ability to pass them as arguments to other functions. This allows for highly flexible and reusable code.
Imagine a function that performs an operation, but what operation it performs is decided by another function you pass to it!
Try running this example:
(ns coddykit.core
(:gen-class))
(defn operate [f x y]
(f x y)) ; Call the function 'f' with arguments 'x' and 'y'
(defn -main [& args]
(println "--- Output ---")
(println (operate + 5 3)) ; Pass the '+' function
(println (operate * 5 3))) ; Pass the '*' functionFunctions that Return Functions
Functions can also create and return new functions. This is useful for building "function factories" that produce specialized functions based on some input.
Here, make-adder takes a number and returns a new function that adds that number to its input.
Try running this example:
(ns coddykit.core
(:gen-class))
(defn make-adder [x]
(fn [y] (+ x y))) ; Returns an anonymous function
(defn -main [& args]
(println "--- Output ---")
(def add-five (make-adder 5))
(def add-ten (make-adder 10))
(println (add-five 2))
(println (add-ten 2)))What are Higher-Order Functions?
When a function either takes one or more functions as arguments, or returns a function as its result, it's called a Higher-Order Function (HOF).
HOFs are incredibly powerful because they allow you to:
- Abstract common patterns.
- Write more concise and expressive code.
- Create flexible and reusable program components.
Let's look at some common HOFs in Clojure!
Transform with `map`
map is a fundamental higher-order function. It applies a given function to each item in a collection (like a list or vector) and returns a new collection containing the results.
It's perfect for transforming data without changing the original collection.
Try running this example:
(ns coddykit.core
(:gen-class))
(defn square [x] (* x x))
(defn -main [& args]
(println "--- Output ---")
(def numbers [1 2 3 4])
(def squared-numbers (map square numbers))
(println "Original numbers:" numbers)
(println "Squared numbers:" squared-numbers))Filter Collections with `filter`
The filter HOF takes a "predicate" function (a function that returns true or false) and a collection. It returns a new collection containing only the elements for which the predicate function returns true.
This is great for selecting specific items from a list.
Try running this example:
(ns coddykit.core
(:gen-class))
(defn is-even? [n]
(= (mod n 2) 0))
(defn -main [& args]
(println "--- Output ---")
(def numbers (range 1 11)) ; Numbers from 1 to 10
(def even-numbers (filter is-even? numbers))
(println "All numbers:" numbers)
(println "Even numbers:" even-numbers))Combine with `reduce`
reduce is another powerful HOF that combines all elements of a collection into a single result. It takes a combining function, an optional initial value, and a collection.
The function is applied cumulatively to each item, often used for summing, finding max/min, or concatenating.
Try running this example:
(ns coddykit.core
(:gen-class))
(defn -main [& args]
(println "--- Output ---")
(def numbers [1 2 3 4 5])
(def sum (reduce + numbers)) ; Sums all numbers
(def product (reduce * numbers)) ; Multiplies all numbers
(println "Numbers:" numbers)
(println "Sum:" sum)
(println "Product:" product))Quick Functions: Lambdas
Often, the functions we pass to HOFs are small and used only once. For these, Clojure provides anonymous functions, also known as lambdas.
They use the shorthand #(...) syntax, where % refers to the first argument, %1 for the first, %2 for the second, and so on.
Try running this example:
(ns coddykit.core
(:gen-class))
(defn -main [& args]
(println "--- Output ---")
(def numbers [1 2 3 4])
(def doubled-numbers (map #(* % 2) numbers)) ; Anonymous function
(def greater-than-two (filter #(> % 2) numbers)) ; Another anonymous function
(println "Doubled:" doubled-numbers)
(println "Greater than 2:" greater-than-two))HOFs in Action
You've learned about first-class and higher-order functions. Now, let's test your understanding of how they can be combined to achieve specific data transformations.
Consider the sequence of numbers (range 1 6), which evaluates to (1 2 3 4 5).
Which Clojure expression correctly uses higher-order functions to get a list of squared even numbers from this sequence?
Recap: Functions as Superpowers
Congratulations! You've unlocked the power of first-class and higher-order functions in Clojure!
Here's what we covered:
- First-Class Functions: Functions can be treated like any other data type – assigned to variables, passed as arguments, and returned from other functions.
- Higher-Order Functions: Functions that operate on other functions (taking them as arguments or returning them).
- Key HOFs: We explored
mapfor transformation,filterfor selection, andreducefor aggregation. - Anonymous Functions: The
#(...)syntax for concise, inline function definitions.
These concepts are central to writing expressive and flexible Clojure code. Keep practicing!
자주 묻는 질문
“일급 함수 및 고차 함수” 강의는 무료인가요?
네 — “일급 함수 및 고차 함수” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Clojure Functional Programming & JVM Backend Development 강의 전체를 잠금 해제할 수 있습니다. Clojure Functional Programming & JVM Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“일급 함수 및 고차 함수”에서 뭘 배우나요?
함수를 값으로 다루는 방법과 함수를 전달하고 강력한 고차 함수를 만드는 방법을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Clojure Functional Programming & JVM Backend Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Clojure Functional Programming & JVM Backend Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Clojure Functional Programming & JVM Backend Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“일급 함수 및 고차 함수” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Clojure Functional Programming & JVM Backend Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Clojure Functional Programming & JVM Backend Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 일급 함수 및 고차 함수
- 불변성 및 영속 데이터
- 지연 시퀀스 및 성능
- 조합 가능한 변환을 위한 변환기