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 Product
s.
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!
See Miles Sabin's Shapeless Shapeless. There is an example of the usage of everywhere in the sybclass test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With