Scala: How to call trim on every element of a Tuple -
i need write function takes tuple of string of size, call trims on each element , returns new tuple. kind of stuck @ point below , code not type safe. in addition not know how go tuple once convert iterator. there more elegant way solve problem? solutions needs work on scala 2.9.2
def trim(input:product)={ input.productiterator.asinstanceof[iterator[string]].map(_.trim) }
if you're willing go solution uses shapeless, pretty straightforward (in shapeless terms, @ least):
import shapeless._ object trimmer extends (string -> string)(_.trim) def trim[t <: product, l <: hlist](t: t)(implicit hlister: hlisteraux[t, l], tolist: tolist[l, string], mapper: mapperaux[trimmer.type, l, l], tupler: tupleraux[l, t] ) = hlister(t).map(trimmer).tupled
and then:
scala> trim((" ", "b ", " c")) res0: (string, string, string) = (a,b,c) scala> trim((" ", "b ", " c", "d")) res1: (string, string, string, string) = (a,b,c,d)
everything's statically typed appropriately, , if try feed tuple non-string
elements, you'll error @ compile time.
without library shapeless—which packages boilerplate you—you're stuck 2 options: give type safety, or write special case every tuple size care (up maximum of 22).
Comments
Post a Comment