Skip to content

Instantly share code, notes, and snippets.

@seraphr
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seraphr/3c65d51b347235e0e8c8 to your computer and use it in GitHub Desktop.
Save seraphr/3c65d51b347235e0e8c8 to your computer and use it in GitHub Desktop.
fp in scala EXERCISE 5.6 foldRightを用いたheadOptionの実装
def foldRight[A, B](s: Stream[A])(z: => B)(f: (A, => B) => B): B = s match {
case x #:: xs => f(x, foldRight(xs)(z)(f))
case _ => z
}
def headOptionViaFoldRight[A](s: Stream[A]): Option[A] = foldRight(s)(None: Option[A]) {
(e, acc) => Some(e)
}
def map[A, B](s: Stream[A])(f: A => B): Stream[B] = foldRight(s)(Stream.empty[B]) {
(e, acc) => f(e) #:: acc
}
def filter[A](s: Stream[A])(f: A => Boolean): Stream[A] = foldRight(s)(Stream.empty[A]) {
(e, acc) => if(f(e)) e #:: acc else acc
}
def append[A](s1: =>Stream[A], s2: =>Stream[A]): Stream[A] = foldRight(s1)(s2) {
(e, acc) => e #:: acc
}
def flatMap[A, B](s: Stream[A])(f: A => Stream[B]): Stream[B] = foldRight(s)(Stream.empty[B]) {
(e, acc) => append(f(e), acc)
}
def n(a: Int) = {println(a); a}
def s = n(1) #:: n(2) #:: n(3) #:: n(4) #:: Stream.empty
headOptionViaFoldRight(s)
map(s)(_ + 2)
filter(s)(_ % 2 == 0)
append(s, map(s)(_ * 3))
flatMap(s)(a => Stream(a, a))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment