7

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!

1 Answer 1

6

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

2
  • Can this take an arbitrary case class and return a new instance based on a function of its parameters, and work with all instances of Product, or is it just limited to tuples? May 3, 2012 at 20:25
  • @LuigiPlinge: this works also with case classes, at least since shapeless 2.0, thanks to macros. A nicer example is here. Mar 9, 2014 at 18:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.