Foldable
#cats
#型クラス
概要
一つの値に集約(要約)可能なコンテナを表す型クラス
foldLeft→((0 + 1) + 2) + 3
foldRight→0 + (1 + (2 + 3))
中身がMonoidな場合はcombineAllで一つの値に折り畳める
例
List,Vector
Option
Scala
code:scala
trait Foldable[F_] extends UnorderedFoldableF with FoldableNFunctionsF { self =>
def foldLeftA, B(fa: FA, b: B)(f: (B, A) => B): B
def foldRightA, B(fa: FA, lb: EvalB)(f: (A, EvalB) => EvalB): EvalB
}
foldRightはEvalを使うことで常にstack safeにしている
code:scala
import cats.syntax.foldable._ // for combineAll and foldMap
List(1, 2, 3).combineAll
// res12: Int = 6
List(1, 2, 3).foldMap(_.toString)
// res13: String = "123"
import cats.data.Nested
val listOption0 = Nested(List(Option(1), Option(2), Option(3)))
// listOption0: NestedList, Option, Int = Nested(
// List(Some(1), Some(2), Some(3))
// )
val listOption1 = Nested(List(Option(1), Option(2), None))
// listOption1: NestedList, Option, Int = Nested(
// List(Some(1), Some(2), None)
// )
Foldable[NestedList, Option, *].fold(listOption0)
// res27: Int = 6
Foldable[NestedList, Option, *].fold(listOption1)
// res28: Int = 3