Fight the Future

Java言語とJVM、そしてJavaエコシステム全般にまつわること

モナドについて調べていく(9)

One Div Zero: Monads are Elephants Part 1の翻訳続き。
モナドがコンテナという例えは今の僕のレベルではわかりやすくていい例えだ。
もちろん完全な説明にはならないのだろうが、概要をイメージしやすくていい。

Monads Support Higher Order Functions(モナド高階関数をサポートする)

A higher order function is a function that takes a function as a parameter or returns a function as a result.

高階関数とは関数が引数となるか戻り値として関数を返す関数です。


Monads are containers which have several higher order functions defined. Or, since we're talking about Scala, monads have several higher order methods.

モナドは定義されたいくつかの高階関数を持つコンテナです。すなわち、Scalaを使っているのでモナドはいくつかの高階メソッドを持つと言えます。


One such method is map. If you know any functional languages then you're probably familiar with map in one form or another.

mapはそのようなメソッドの1つです。もし関数型言語を知っているならおそらくmapの1つか2つの形に親しんでいるでしょう。


The map method takes a function and applies it to each element in the container to return a new container.

mapメソッドは関数を引数に取り、コンテナの各要素にそれを適用して新しいコンテナを返します。


For instance

たとえば

def double(x: Int) = 2 * x
val xs = List(1, 2, 3)
val doubles = xs map double
// or val doubles = xs map {2 * _}
assert(doubles == List(2, 4, 6))

Map does not change the kind of monad, but may change its parameterized type...

mapはモナドの種類は変えませんが、そのパラメータ化された型を変えられます。

val one = Some(1)
val oneString = one map {_.toString}
assert(oneString == Some("1"))

Here the {_.toString} notation means that the toString method should be called on the element.

ここで{_.toString}表記が意味することは要素のtoStringメソッドを呼び出すということです。