scala - Change while loop to Stream but missing the last element -


i've tried replace while loop stream when use stream version, last element missing. think understand why it's missing can't figure how fix this. suggesting? there better way this? thanks

using stream:

if(cursor.movetofirst) { val result = stream.continually((   song(     cursor.getlong(c(basecolumns._id)),     cursor.getstring(c(mediacolumns.title))        ),   cursor.movetonext)) .takewhile(_._2) .map(_._1) result.tolist } 

here while loop version works fine.

cursor.movetofirst() var = 0 var list: list[song] = list.empty while (i < cursor.getcount()) {   val s = song(     cursor.getlong(c(basecolumns._id)),     cursor.getstring(c(mediacolumns.title)))   = + 1   list = list :+ s   cursor.movetonext() 

note:

movetonext

move cursor next row. method return false if cursor past last entry in result set.

suppose have 1 entry. produce tuple

(song, false) 

and throw away. that's no good. want keep song though there's not another song there! instead might try option--load song if there one, don't if there isn't. have handle first element differently since movetofirst not same movetonext. so:

def loadsong = song(   cursor.getlong(c(basecolumns._id)),   cursor.getstring(c(mediacolumns.title))      )  if (cursor.movetofirst) {   val songs = stream(some(loadsong)) ++     stream.continually(if (cursor.movetonext()) some(loadsong) else none)   songs.flatten.tolist } 

note you're not using streaminess of streams here, use iterator.continually.

note: might instead move wrapping logic somelong , produce instead:

def loadsong(b: boolean) = if (!b) none else some(song(   cursor.getlong(c(basecolumns._id)),   cursor.getstring(c(mediacolumns.title))      ))  val songs = stream(loadsong(cursor.movetofirst())) ++     stream.continually(loadsong(cursor.movetonext()) songs.flatten.tolist 

or, given method have in personal library:

def optin[a](b: boolean)(a: => a) = if (b) some(a) else none 

the plain loadsong before with

val songs = stream(optin(cursor.movetofirst)(loadsong)) ++   stream.continually(optin(cursor.movetonext)(loadsong)) songs.flatten.tolist 

is compact , readable. (once know how read optin.)


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -