Last active
August 29, 2015 14:24
-
-
Save seraphr/3c65d51b347235e0e8c8 to your computer and use it in GitHub Desktop.
fp in scala EXERCISE 5.6 foldRightを用いたheadOptionの実装
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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