0Pricing
Clojure Functional Programming & JVM Backend Development · レッスン

第一級関数と高階関数

関数を値として扱う方法、関数を受け渡す方法、強力な高階関数を作成する方法を理解します。

「第一級関数と高階関数」はCoddyKit上の無料Clojure Functional Programming & JVM Backend Developmentレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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 '*' function

Functions 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 map for transformation, filter for selection, and reduce for aggregation.
  • Anonymous Functions: The #(...) syntax for concise, inline function definitions.

These concepts are central to writing expressive and flexible Clojure code. Keep practicing!

よくある質問

「第一級関数と高階関数」レッスンは無料ですか?

はい。「第一級関数と高階関数」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Clojure Functional Programming & JVM Backend Developmentコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Clojure Functional Programming & JVM Backend Developmentコースには全4レッスンが含まれています。

「第一級関数と高階関数」で何を学びますか?

関数を値として扱う方法、関数を受け渡す方法、強力な高階関数を作成する方法を理解します。 ブラウザで直接実行するハンズオンコードでClojure Functional Programming & JVM Backend Developmentを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Clojure Functional Programming & JVM Backend Developmentを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのClojure Functional Programming & JVM Backend Developmentは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「第一級関数と高階関数」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このClojure Functional Programming & JVM Backend Developmentレッスンでコードを書いて実行できますか?

はい。すべてのClojure Functional Programming & JVM Backend Developmentレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. 第一級関数と高階関数
  2. 不変性と永続データ
  3. 遅延シーケンスとパフォーマンス
  4. 合成可能な変換のためのトランスデューサー
← Clojure Functional Programming & JVM Backend Developmentに戻る