You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Implement [...] scanLeft on Stream. They have the same semantics as the same methods on List, [...]
The behaviour of Lists scanLeft is as follows:
scala>defincrement(x: Int, y: Int):Int= x + y
defincrement(x: Int, y: Int):Int
scala>List.fill(5)(1).scanLeft(0)(increment)
valres0:List[Int] =List(0, 1, 2, 3, 4, 5)
However, using the solution provided by the book for Stream gives the following result (using the book's prior definition of ones):
scala>defincrement(x: Int, y: Int):Int= x + y
defincrement(x: Int, y: Int):Int
scala> ones.scanLeft(0)(increment).take(6)
valres0:List[Int] =List(1, 2, 3, 4, 5, 6)
The difference being that while List's scanLeft includes the zero value in the resulting List as-is, Stream's does not, instead applying f to zero and self.head as the first element of the resulting Stream. An implementation of scanLeft for Stream that follows the one in List could instead look like:
defscanLeft[B](zero: B)(f: (B, A) =>B):Stream[B] = {
valself=thisnewStream[B] {
defhead:B= zero
deftail:Stream[B] = self.tail.scanLeft(f(zero, self.head))(f)
}
}
The text was updated successfully, but these errors were encountered:
"Exercise: Stream Combinators" asks:
The behaviour of
List
sscanLeft
is as follows:However, using the solution provided by the book for
Stream
gives the following result (using the book's prior definition ofones
):The difference being that while
List
'sscanLeft
includes thezero
value in the resultingList
as-is,Stream
's does not, instead applyingf
tozero
andself.head
as the first element of the resultingStream
. An implementation ofscanLeft
forStream
that follows the one inList
could instead look like:The text was updated successfully, but these errors were encountered: