How can I transform a list of Strings into another form in Scala? -
i have list of strings take following form:
000000 011220 011220 033440 033440 000000
i'd transform these strings list of values represents each 2x2 block while preserving row information. irrelevant whether data representing each 2x2 block stored in list or tuple. example, 2x2 block representing upper left corner in 1 of following forms:
(0, 0, 0, 1) list((0, 0), (0, 1)) list(0, 0, 0, 1) list(list(0, 0), list(0, 1))
the scala code below performs prescribed transformation, seems overly complex. can break of functionality separate functions, cannot see how code can converted simpler form for-comprehension.
note: i've simplified list of values brevity.
scala> val data = list("000000", "011220", "033440") data: list[string] = list(000000, 011220, 033440) scala> val values = (data map { _.tolist.sliding(2).tolist } sliding(2) map { _.transpose } map { _ map { _.flatten } }).tolist values: list[list[list[char]]] = list(list(list(0, 0, 0, 1), list(0, 0, 1, 1), list(0, 0, 1, 2), list(0, 0, 2, 2), list(0, 0, 2, 0)), list(list(0, 1, 0, 3), list(1, 1, 3, 3), list(1, 2, 3, 4), list(2, 2, 4, 4), list(2, 0, 4, 0)))
for clarity, i've relabeled of lists 'row' , 'block', not represent concrete classes. monikers present more meaningful view of output above.
values: list[row[block[char]]] = list(row(block(0, 0, 0, 1), block(0, 0, 1, 1), ...), row(block(0, 1, 0, 3), block(1, 1, 3, 3), ...))
i relatively new scala , i'd know if code represented above way implement transformation or there more elegant way?
you way (the .tolist
here see results instead of non-empty iterator
) :
scala> val values = data.map(_.sliding(2).tolist) // create sliding window on consecutive characters .sliding(2).tolist // slide on consecutive rows .flatmap { case list(row1, row2) => row1 zip row2 } // zip rows together, creating blocks values: list[(string, string)] = list((00,01), (00,11), (00,12), (00,22), (00,20), (01,03), (11,33), (12,34), (22,44), (20,40))
Comments
Post a Comment