ExampleChap5

「ExampleChap5」の編集履歴(バックアップ)一覧に戻る

ExampleChap5 - (2008/04/19 (土) 11:55:41) のソース

* Chapter 5 First-Class Functions

A function in Scala is a “first-class value”. Like any other value, it may be passed as a parameter or returned as a result. Functions which take other functions as parameters or return them as results are called higher-order functions. This chapter introduces higher-order functions and shows how they provide a flexible mechanism for program composition. 

Scala の関数は「第一級の値」です。他の他の値のように、仮引数として渡したり結果として受け取る事が出来ます。他の関数を仮引数として取ったり、関数を結果として返す関数は、「高階関数」と呼ばれます。この章では高階関数を紹介し、プログラム作成にとってどれほど柔軟なメカニズムを与えるかを示します。

As a motivating example, consider the following three related tasks: 

動機付けの例として次の三つの関連した作業を考えます。

1. Write a function to sum all integers between two given numbers a and b: 

1. 二つのあたえられた数 a と b との間の整数の和を求める関数を書きなさい。

 def sumInts(a: Int, b: Int): Int = 
   if (a > b) 0 else a + sumInts(a + 1, b)

2. Write a function to sum the squares of all integers between two given numbers a and b: 

2. 二つのあたえられた数 a と b との間の整数の二乗の和を求める関数を書きなさい。

 def square(x: Int): Int = x * x 
 def sumSquares(a: Int, b: Int): Int = 
   if (a > b) 0 else square(a) + sumSquares(a + 1, b) 

3. Write a function to sum the powers 2n of all integers n between two given numbers a and b: 

3. 二つのあたえられた数 a と b との間の整数 n について 2^n の和を求める関数を書きなさい。

 def powerOfTwo(x: Int): Int = if (x == 0) 1 else 2 * powerOfTwo(x - 1) 
 def sumPowersOfTwo(a: Int, b: Int): Int = 
   if (a > b) 0 else powerOfTwo(a) + sumPowersOfTwo(a + 1, b) 

These functions are all instances of Σ^b_a f (n) for different values of f . We can factor out the common pattern by defining a function sum: 

これらの関数は全て異なる値 f についてのΣ^b_a f(n) のインスタンスです。関数 sum を定義する事で共通パターンを括り出すことが出来ます。

 def sum(f: Int => Int, a: Int, b: Int): Int = 
   if (a > b) 0 else f(a) + sum(f, a + 1, b)

The type Int => Int is the type of functions that take arguments of type Int and return results of type Int. So sum is a function which takes another function as a parameter. In other words, sum is a higher-order function. 

型 Int => Int は型 Int の引数を取って、型 Int の結果を返す関数の型です。従って sum は他の関数を仮引数として取る関数です。別の言葉で言えば sum は「高階関数」です。

Using sum, we can formulate the three summing functions as follows. 

sum を使う事で和を求める三つの関数を下記の様に定式化出来ます。

 def sumInts(a: Int, b: Int): Int = sum(id, a, b) 
 def sumSquares(a: Int, b: Int): Int = sum(square, a, b) 
 def sumPowersOfTwo(a: Int, b: Int): Int = sum(powerOfTwo, a, b) 

where 

但し、

 def id(x: Int): Int = x 
 def square(x: Int): Int = x * x 
 def powerOfTwo(x: Int): Int = if (x == 0) 1 else 2 * powerOfTwo(x - 1) 

- [[5.1 Anonymous Functions>Example5.1]]
- [[5.2 Currying>Example5.2]]
- [[5.3 Example: Finding Fixed Points of Functions>Example5.3]]
- [[5.4 Summary>Example5.4]]
- [[5.5 Language Elements Seen So Far>Example5.5]]

----
#comment
ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。