Monad
|
Term |
monad |
|
Aliases |
- |
Definition
A monad is an abstraction for chaining computations in a context. It consists primarily of flatMap (or bind ) and pure (or unit ), allowing safe, composable expression of sequential operations, state handling, and error propagation in a functional style.
Scala
Catsにおける型クラス Monad の定義は次のようになります。
trait Monad[F[_]] extends FlatMap[F] with Applicative[F] {
def pure[A](a: A): F[A]
def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B]
}
この定義により、任意の型 F[_] に対し、 pure と flatMap の実装を与えることでモナドとして扱うことができます。 Catsでは、 for 式や >>= 相当の連結操作、 map / flatMap チェーンをこの型クラスによって一般化しています。