Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrap Your Boilerplate equivalent in Scala?

Tags:

haskell

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!

like image 752
Todd O'Bryan Avatar asked May 02 '12 23:05

Todd O'Bryan


1 Answers

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

like image 89
Arjan Blokzijl Avatar answered Oct 18 '22 06:10

Arjan Blokzijl