|
| 1 | +/* __ *\ |
| 2 | +** ________ ___ / / ___ Scala API ** |
| 3 | +** / __/ __// _ | / / / _ | (c) 2003-2012, LAMP/EPFL ** |
| 4 | +** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** |
| 5 | +** /____/\___/_/ |_/____/_/ | | ** |
| 6 | +** |/ ** |
| 7 | +\* */ |
| 8 | + |
| 9 | +package scala.collection |
| 10 | +package generic |
| 11 | + |
| 12 | +/** Type class witnessing that a collection representation type `Repr` has |
| 13 | + * elements of type `A` and has a conversion to `GenTraversableLike[A, Repr]`. |
| 14 | + * |
| 15 | + * This type enables simple enrichment of `GenTraversable`s with extension |
| 16 | + * methods which can make full use of the mechanics of the Scala collections |
| 17 | + * framework in their implementation. |
| 18 | + * |
| 19 | + * Example usage, |
| 20 | + * {{{ |
| 21 | + * import scala.collection.generic.{ CanBuildFrom, FromRepr, HasElem } |
| 22 | + * |
| 23 | + * class FilterMapImpl[A, Repr](val r : Repr)(implicit hasElem : HasElem[Repr, A]) { |
| 24 | + * def filterMap[B, That](f : A => Option[B]) |
| 25 | + * (implicit cbf : CanBuildFrom[Repr, B, That]) : That = r.flatMap(f(_).toSeq) |
| 26 | + * } |
| 27 | + * |
| 28 | + * implicit def filterMap[Repr : FromRepr](r : Repr) = new FilterMapImpl(r) |
| 29 | + * |
| 30 | + * val l = List(1, 2, 3, 4, 5) |
| 31 | + * List(1, 2, 3, 4, 5) filterMap (i => if(i % 2 == 0) Some(i) else None) |
| 32 | + * // == List(2, 4) |
| 33 | + * }}} |
| 34 | + * |
| 35 | + * @author Miles Sabin |
| 36 | + * @since 2.10 |
| 37 | + */ |
| 38 | +trait FromRepr[Repr] { |
| 39 | + type A |
| 40 | + val hasElem: HasElem[Repr, A] |
| 41 | +} |
| 42 | + |
| 43 | +object FromRepr { |
| 44 | + import language.higherKinds |
| 45 | + |
| 46 | + implicit val stringFromRepr : FromRepr[String] { type A = Char } = new FromRepr[String] { |
| 47 | + type A = Char |
| 48 | + val hasElem = implicitly[HasElem[String, Char]] |
| 49 | + } |
| 50 | + |
| 51 | + implicit def genTraversableLikeFromRepr[C[_], A0] |
| 52 | + (implicit hasElem0: HasElem[C[A0], A0]) : FromRepr[C[A0]] { type A = A0 } = new FromRepr[C[A0]] { |
| 53 | + type A = A0 |
| 54 | + val hasElem = hasElem0 |
| 55 | + } |
| 56 | +} |
0 commit comments