AlexeyKarasev
AlexeyKarasev

Reputation: 520

Map whole list in Scala

I want to be able to do smth like this

List(1, 2, 3).someFunc?(list => List(list, list)) // List(List(1,2,3), List(1,2,3))

The general idea is I want smth like map, but acting not on the elements of the list, but on the whole list itself. Alternative is to write smth like this:

val list = List(1, 2, 3)
val res = List(list, list)

But I'd like some function that could be used in chains. Is there a function like this?

EDIT: Ideally I'd like to chain map over elements and this "kind of map" for the whole list interchangably, e.g.

 List(1, 2, 3).map(_ + 1).someFunc?(list => List(list, list))

Upvotes: 3

Views: 794

Answers (3)

akuiper
akuiper

Reputation: 215127

I think you can use a pattern matching here:

List(1, 2, 3) match { case x => List(x, x) }
// res25: List[List[Int]] = List(List(1, 2, 3), List(1, 2, 3))

Upvotes: 1

Cyrille Corpet
Cyrille Corpet

Reputation: 5305

You can easily define your own operator:

implicit class RichList[T](l: List[T]){
  def applyFun[U](f: List[T] => U): U = f(l)
}

You can even add some restriction on the output type of the function that can be applied, eg if you want to make sure that the output is still a list (just replace U with List[U] as the output of f and the output of applyFun[U]).

Upvotes: 2

Matt Fowler
Matt Fowler

Reputation: 2743

I think an option suits your needs well:

Option(List(1, 2, 3)).map(lst => List(lst, lst))

You may also want to consider streams:

Stream.continually(List(1, 2, 3)).take(2).toList

You can then map over this list of lists however you want.

Upvotes: 1

Related Questions