Iterable with two elements?

We have Optionwhich is Iterableover 0 or 1 elements.

I would like to have such a thing with two elements. The best I have:

Array(foo, bar).map{...}although I would like to:

(foo, bar).map{...}

(such that Scala recognizes that Iterablethere are two elements in).

Does such a design exist in the standard library?

EDIT: another solution is to create a method map:

def map(a:Foo) = {...}

val (mappedFoo, mappedBar) = (map(foo), map(bar))
+4
source share
3 answers

If all you want to do is map on tuples of the same type, simple version:

implicit class DupleOps[T](t: (T,T)) {
  def map[B](f : T => B) = (f(t._1), f(t._2))
}

Then you can do the following:

val t = (0,1)
val (x,y) = t.map( _ +1)  // x = 1, y = 2

There is no specific type in the scala standard library to display on exactly 2 elements.

+3
source

( , foo bar T):

(foo, bar)                         // -> Tuple2[T,T]
  .productIterator             // -> Iterator[Any]
  .map(_.asInstanceOf[T])    // -> Iterator[T]
  .map(x => // some works)
+2

, .

  • .

  • Write an implicit conversion from 2 tuples to a Seqcommon supertype. But this will not give 2 tuples from operations.

    object TupleOps {
        implicit def tupleToSeq[A <: C, B <: C](tuple: (A, B)): Seq[C] = Seq(tuple._1,tuple._2)
    }
    
    import TupleOps._
    
    (0, 1).map(_ + 1)
    
  • Use hlists from formless. They provide operations on heterogeneous lists, while you (probably?) Have a uniform list, but it should work.

+1
source

All Articles