Fight the Future

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

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

Monads in Scala前回に引き続き翻訳。

Computation(計算法)

In programming, the prime use of constructing a monad is to build objects which are computations.

プログラミングにおいて、モナドを構成する主要な用途は計算法であるオブジェクトを構築するためです。


These computations are things that are waiting to be carried out.

これらの計算法は実施するまで待機しているものです。


Presumably, the programmer has some interest in not carrying them out directly (for instance the computation to be done is not fully known at compile-time; check Gamma's Command design pattern).

おそらく、プログラマは直接それらを実行しないことに興味があります(たとえば実行される計算がコンパイル時に完全にわからないなど。ガンマのデザインパターンにあるコマンドパターンを参照のこと)。


In those paper mentioned before, a monad is always described as some type constructor M and two functions unit, bind with these types:

上述した論文において、モナドは常にある型のコンストラクタMとそれらの型を利用する2つの関数unit,bindとして記述されます。

  • def unit: a -> M[b]
  • def bind: M[a] -> (a->M[b]) -> M[b]
jyukutyoコメント

なるほど。だからScalaのExampleでも

  case class M[A](value: A) {
    def bind[B](k: A => M[B]): M[B] = k(value)
    def map[B](f: A => B): M[B] = bind(x => unitM(f(x)))
    def flatMap[B](f: A => M[B]): M[B] = bind(f)
  }

  def unitM[A](a: A) = M(a)

と定義しているわけか。
でも

  • def bind: M[a] -> (a->M[b]) -> M[b]
  • def bind[B](k: A => M[B]): M[B] = k(value)

は同じ??判断できない。。。


(Where is the connection to the theory?

理論はどこでつながっているのか?


Call M a functor T, unit a natural transformation eta, and call mu: M[M[a]] -> M[a] another natural transformation.

MをファンクターTとし、unitをetaの自然変換とし、mu: M[M[a]] -> M[a]をもう1つの自然変換とします。


※自然変換とは

Natural transformation(自然変換) とは、そのカテゴリのオブジェクトに影響を与えたり与えら
れたりせずに、ある構造から別の構造への変換を行うことである。

http://www.itpl.co.jp/ocaml-nagoya/index.php?plugin=attach&refer...dontpanic03.pdf

The functor T lifts any function f:a-<b to a function Tf:T[A] -> T[B], so one can see that the mu is kind of hidden in the bind.

ファンクターTはあらゆる関数f:a-<bを関数Tf:T[A] -> T[B]に上げます。そのためmuはbindにおいてやや隠れていると考えられます。


bind is called a Kleisli extension, (M, unit, bind) a Kleisli triple. mu is also known as flatten or join.

bindはKleisliの拡張と呼ばれます。(M, unit, bind)はKleisli tripleです。muはまたフラット化する、または結合するものとして知られています。


The ability of the functor T of lifting functions is often done by a function called map

関数を上げるものであるファンクターTの能力はしばしばmapと呼ばれる関数によって実行されます。


To stay with the List example from above, take bind (x) (f) to be flatten(map(f)(x)).

上記のリストの例で言うと、bind (x) (f)がflatten(map(f)(x))になります。


This explains the use of the name flatMap in Scala code.

これはScalaコードにおける名前flatMapの使用法を説明しています。


In the tutorial, we will continue to use bind to avoid confusion.

チュートリアルでは、混乱を避けるためにbindを使い続けることにします。


These functions must satisfy certain laws (Kleisli laws, also called monad laws):

これらの関数はある法則を満たさなければなりません(Kleisliの法則またはモナド則と呼ばれる)

  • bind(unit(t),{b=>y}) == y[t/b]
  • bind(m, {x => unit x} == m
  • bind(m, {x=> bind(n, {y=> o}} == bind(bind(m, {x=>n}), {y=>o}) (if x ∉ fv(o))


※x ∉ fv(o)はxがfv(o)の集合に属さないということ。