摘要:
package either object Traverse { def traverse[E, A, B](as: List[A])(f: A => Either[E, B]): Either[E, List[B]] = as match { case Nil => Right(Nil) case h :: t => f(h) flatMap (hh => tra... 阅读全文
摘要:
package either object Sequence { def sequence[E, A](es: List[Either[E, A]]): Either[E, List[A]] = es match { case Nil => Right(Nil) case h :: t => h flatMap (hh => sequence(t) map (tt ... 阅读全文
摘要:
package either trait Either[+E, +A] { def map[B](f: A => B): Either[E, B] = this match { case Left(e) => Left(e) case Right(a) => Right(f(a)) } def flatMap[EE >: E, B](f: A => Eithe... 阅读全文
摘要:
package option object Traverse { def traverse[A, B](a: List[A])(f: A => Option[B]): Option[List[B]] = a match { case Nil => Some(Nil) case h :: t => Map2.map2(f(h), traverse(t)(f))(_ :... 阅读全文
摘要:
package tree object DepthByFold { def depth[A](t: Tree[A]): Int = Fold.fold(t)(_ => 0)((a, b) => (a max b) + 1) def main(args: Array[String]): Unit = { val tree = Branch(Leaf(1), Branch(Br... 阅读全文
摘要:
package tree object MaximumByFold { def maximum(t: Tree[Int]): Int = Fold.fold(t)(a => a)(_ max _) def main(args: Array[String]): Unit = { val tree = Branch(Leaf(1), Branch(Branch(Branch(L... 阅读全文
摘要:
package tree object Fold { def fold[A, B](t: Tree[A])(f: A => B)(g: (B, B) => B): B = t match { case Leaf(a) => f(a) case Branch(l, r) => g(fold(l)(f)(g), fold(r)(f)(g)) } def m... 阅读全文
摘要:
package tree object Depth { def depth[A](t: Tree[A]): Int = t match { case Leaf(_) => 0 case Branch(l, r) => (depth(l) max depth(r)) + 1 } def main(args: Array[String]): Unit = ... 阅读全文
摘要:
package tree object Maximum { def maximum(t: Tree[Int]): Int = t match { case Leaf(n) => n case Branch(l, r) => maximum(l) max maximum(r) } def main(args: Array[String]): Unit =... 阅读全文
摘要:
package tree sealed trait Tree[+A] case class Leaf[A](value: A) extends Tree[A] case class Branch[A](left: Tree[A], right: Tree[A]) extends Tree[A] 阅读全文
摘要:
object Filter { def filter[A](as: List[A])(f: A => Boolean): List[A] = FoldRight.foldRight(as, Nil: List[A])((a: A, b: List[A]) => if (f(a)) a :: b else b) def main(args: Array[String]): Unit =... 阅读全文
摘要:
object FoldLeft { def foldLeft[A, B](as: List[A], z: B)(f: (B, A) => B): B = as match { case Nil => z case h :: t => foldLeft(t, f(z, h))(f) } def main(args: Array[String... 阅读全文
摘要:
object FoldRight { def foldRight[A, B](as: List[A], z: B)(f: (A, B) => B): B = as match { case Nil => z case ::(x, xs) => f(x, foldRight(xs, z)(f)) } def main(args: Ar... 阅读全文