Example5.1

「Example5.1」の編集履歴(バックアップ)一覧に戻る
Example5.1」を以下のとおり復元します。
** 5.1 Anonymous Functions

Parameterization by functions tends to create many small functions. In the previous example, we defined id, square and power as separate functions, so that they could be passed as arguments to sum. 

Instead of using named function definitions for these small argument functions, we can formulate them in a shorter way as anonymous functions. An anonymous function is an expression that evaluates to a function; the function is defined without giving it a name. As an example consider the anonymous square function: 

 (x: Int) => x * x 

The part before the arrow ‘=>’ are the parameters of the function, whereas the part following the ‘=>’ is its body. For instance, here is an anonymous function which multiples its two arguments. 

 (x: Int, y: Int) => x * y 

Using anonymous functions, we can reformulate the first two summation functions without named auxiliary functions: 

 def sumInts(a: Int, b: Int): Int = sum((x: Int) => x, a, b) 
 def sumSquares(a: Int, b: Int): Int = sum((x: Int) => x * x, a, b) 

Often, the Scala compiler can deduce the parameter type(s) from the context of the anonymous function in which case they can be omitted. For instance, in the case of sumInts or sumSquares, one knows from the type of sum that the first parameter must be a function of type Int => Int. Hence, the parameter type Int is redundant and may be omitted. If there is a single parameter without a type, we may also omit the parentheses around it: 

 def sumInts(a: Int, b: Int): Int = sum(x => x, a, b) 
 def sumSquares(a: Int, b: Int): Int = sum(x => x * x, a, b) 

Generally, the Scala term (x1 : T1 , ..., xn : Tn ) => E defines a function which maps its parameters x1 , ..., xn to the result of the expression E (where E may refer to x1 , ..., xn ). Anonymous functions are not essential language elements of Scala, as they can always be expressed in terms of named functions. Indeed, the anonymous function 

 (x1 : T1, ..., xn : Tn ) => E 

is equivalent to the block

 { def f (x1 : T1, ..., xn : Tn ) = E ; f _ } 

where f is fresh name which is used nowhere else in the program. We also say, anonymous functions are “syntactic sugar”. 

----
#comment

復元してよろしいですか?

ツールボックス

下から選んでください:

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