Skip to content

Commit

Permalink
Merge pull request #48 from scala/flatten
Browse files Browse the repository at this point in the history
Flatten and interaction between flatMap and Options
  • Loading branch information
julienrf committed Jun 27, 2017
2 parents c6d1aa1 + a45814a commit 4da00e3
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/main/scala/strawman/collection/Iterable.scala
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,9 @@ trait IterableOps[+A, +CC[X], +C] extends Any {
/** Flatmap */
def flatMap[B](f: A => IterableOnce[B]): CC[B] = fromIterable(View.FlatMap(coll, f))

def flatten[B](implicit ev: A => IterableOnce[B]): CC[B] =
fromIterable(View.FlatMap(coll, ev))

/** Returns a new $coll containing the elements from the left hand operand followed by the elements from the
* right hand operand. The element type of the $coll is the most specific superclass encompassing
* the element types of the two operands.
Expand Down
9 changes: 8 additions & 1 deletion src/main/scala/strawman/collection/package.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package strawman

import scala.{Any, AnyVal, Array, Char, IllegalArgumentException, IndexOutOfBoundsException, Int, NoSuchElementException, Unit, UnsupportedOperationException}
import scala.{Any, AnyVal, Array, Boolean, Char, IllegalArgumentException, IndexOutOfBoundsException, Int, NoSuchElementException, Unit, UnsupportedOperationException}
import scala.Predef.String
import scala.reflect.ClassTag

Expand Down Expand Up @@ -71,6 +71,13 @@ package object collection extends LowPriority {
}
}

implicit def optionToIterableOnce[A](maybeA: scala.Option[A]): IterableOnce[A] =
new Iterator[A] {
private var _hasNext = maybeA.nonEmpty
def next(): A = if (_hasNext) { _hasNext = false; maybeA.get } else Iterator.empty.next()
def hasNext: Boolean = _hasNext
}

}

class LowPriority {
Expand Down
23 changes: 23 additions & 0 deletions src/test/scala/strawman/collection/test/FlattenTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package strawman
package collection.test

import org.junit.Test
import strawman.collection.Seq
import strawman.collection.immutable.{ImmutableArray, List}

import scala.{Int, Some, Unit}
import scala.Predef.{$conforms, assert}

class FlattenTest {

def f(xs: Seq[Seq[Int]], ys: Seq[Int]): Unit = {
assert(xs.flatten == ys)
assert(ys.flatMap(y => Some(y)) == ys.map(y => Some(y)).flatten)
}

@Test
def flattenTest: Unit = {
f(List(ImmutableArray(1, 2, 3)), List(1, 2, 3))
}

}

0 comments on commit 4da00e3

Please sign in to comment.