Thursday, March 4, 2010

Zip with a constant value

A simple tip for zipping a List (or other collection) with a single value.

  1. scala> Stream.continually("h") zip List(1,2,3,4)
  2. res2: scala.collection.immutable.Stream[(java.lang.String, Int)] = Stream((h,1), ?)
  3. scala> res2 mkString ","
  4. res3: String = (h,1),(h,2),(h,3),(h,4)
  5. scala> List(1,2,3,4) zip Stream.continually("h")
  6. res4: List[(Int, java.lang.String)] = List((1,h), (2,h), (3,h), (4,h))

2 comments:

  1. Hi,

    Wouldn't map be more appropriate in this case ?

    List(1, 2, 3, 4) map ((_, "h"))

    Cheers.

    ReplyDelete
  2. jawher> I guess the stream version is lazy, but you can change your idea to:

    List(1, 2, 3, 4).view map ((_, "h"))

    That should make it lazy aswell I guess.

    ReplyDelete