Todd O'Bryan
Todd O'Bryan

Reputation: 2260

Scrap Your Boilerplate equivalent in Scala?

Haskell has this cool generic traversal stuff that lets you call something like map on every node in a collection, either bottom-up or top-down. It's called everywhere and you'd do something like everywhere f tree and f would be called on every node in your tree.

Writing something equivalent in Scala for Traversable is easy, but Haskell's also works on tuples and the equivalent of case classes or, more generically, what Scala calls Products.

You can traverse over the elements in a Product using the productIterator method, but is there some easy way to put a tuple or a case class back together once you know what the arguments to the constructor (actually, I guess the apply method) should be?

def mapOnProduct[X](f: X -> X, prod: Product) {
  val newArgs = prod.productIterator.map {
    case x: X => f(x)
    case id => id
  }.toList
  [?].apply(newArgs: _*)
}

What can I replace [?] with so that this has some chance of working?

Thanks!

Upvotes: 7

Views: 1043

Answers (1)

Arjan Blokzijl
Arjan Blokzijl

Reputation: 6888

See Miles Sabin's Shapeless Shapeless. There is an example of the usage of everywhere in the sybclass test

Upvotes: 6

Related Questions