Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. package java2scala.homeworks.funcs
  2.  
  3. trait ChurchList[A] {
  4. def fold[B](z: B)(f: A => B => B): B
  5.  
  6. def ::(x: A): ChurchList[A] = new ChurchList.Cons[A](this, x)
  7.  
  8. def map[B](f: A => B): ChurchList[B] = fold(ChurchList.empty[B])(e => acc => f(e) :: acc)
  9. def filter(f: A => Boolean): ChurchList[A] = fold(ChurchList.empty[A])(e => acc => if (f(e)) e :: acc else acc)
  10. def flatMap[B](f: A => ChurchList[B]): ChurchList[B] = fold(ChurchList.empty[B])(e => acc => f(e) ++ acc)
  11. def headOption: Option[A] = fold(Option.empty[A])(e => _ => Some(e))
  12. def drop(count: Int): ChurchList[A] =
  13. fold((ChurchList.empty[A], 0))(e => acc => if (acc._2 < count) (acc._1, acc._2 + 1) else (e :: acc._1, acc._2 + 1))._1
  14. def toList: List[A] = fold(List[A]())(e => acc => e :: acc)
  15. def ++(that: ChurchList[A]): ChurchList[A] = fold(that)(e => acc => e :: acc)
  16. }
  17.  
  18. object ChurchList {
  19. def apply[A](xs: A*): ChurchList[A] = {
  20. def go(seq: Seq[A], acc: ChurchList[A]): ChurchList[A] = seq match {
  21. case Seq() => acc
  22. case h +: tail => go(tail, h :: acc)
  23. }
  24.  
  25. go(xs.reverse, empty[A])
  26. }
  27.  
  28. def empty[A]: ChurchList[A] = new ChurchList[A] {
  29. override def fold[B](z: B)(f: A => B => B): B = z
  30. }
  31.  
  32. class Cons[A] private[ChurchList] (list: ChurchList[A], x: A) extends ChurchList[A] {
  33. override def fold[B](z: B)(f: A => B => B): B = f(x)(list.fold(z)(f))
  34. }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement