collections - Scala: Fill the gaps in a List with last non-empty value -


i have list like:

val arr = array("a", "", "", "b", "c", "") 

i looking way create:

array("a", "a", "a", "b", "c", "c") 

you can try fold, easy (to understand) approach fold left:

(array.empty[string] /: arr) {     case (prev, "") => prev :+ prev.lastoption.getorelse("");     case (prev, l) => prev :+ l }  > res01: array[string] = array(a, a, a, b, c, c) 

this builds new array previous appending arr elements or resulting list's last depending on whether source element empty string or not.

you can write as:

(array.empty[string] /: arr) {     case (array(), l) => array(l)     case (prev, "") => prev :+ prev.last;     case (prev, l) => prev :+ l } 

it can optimized using lists , prepend:

{(list.empty[string] /: arr) {     case (nil, l) => l::nil     case (h::tail, "") => h::h::tail;     case (prev, l) => l::prev } reverse } toarray 

in case don't symbolic version of fold left , fold right methods. here comes textual identifier:

arr.foldleft(array.empty[string]) {     case (prev, "") => prev :+ prev.lastoption.getorelse("");     case (prev, l) => prev :+ l }  arr.foldleft(list.empty[string]) {     case (nil, l) => l::nil     case (h::tail, "") => h::h::tail;     case (prev, l) => l::prev }.reverse toarray 

its same approach , implementation different name.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -