collections - Scala unFlatMap -


i perform unflatmap. lets have stream:

stream("|","a","d","a","m","|","j","o","h","n", ...)

stream infinite. convert to:

stream("adam", "john", ...)

ofcourse example. in general perform operation on elements separated delimiter, generic signature be:

def unflatmap[b](isseparator:a => boolean)(group:seq[a] => b):traversableonce[b]

how in clean , memory efficient way?

you this:

def groupstream[a, b](s: stream[a])(isseparator: => boolean)(group: seq[a] => b): stream[b] =    group(s.takewhile(!isseparator(_)).tolist) #:: groupstream(s.dropwhile(!isseparator(_)).drop(1))(isseparator)(group) 

or if want easier read more verbose version:

def groupstream[a, b](s: stream[a])(isseparator: => boolean)(group: seq[a] => b): stream[b] = {   def isnotseparator(i: a): boolean = ! isseparator(i)    def dogroupstream(s: stream[a]): stream[b] =      group(s.takewhile(isnotseparator).tolist) #:: dogroupstream(s.dropwhile(isnotseparator).drop(1))    dogroupstream(s) } 

if want implicit method on stream,

implicit class improvedstream[a](val s: stream[a]) extends anyval {     def groupstream[b](isseparator: => boolean)(group: seq[a] => b): stream[b] = {       def isnotseparator(i: a): boolean = ! isseparator(i)        def dogroupstream(st: stream[a]): stream[b] =          group(st.takewhile(isnotseparator).tolist) #:: dogroupstream(st.dropwhile(isnotseparator).drop(1))        dogroupstream(s)     } } 

now, using example:

val = stream("|" ,"a","d","a","m","|","j","o","h","n", "|", "m", "a", "r", "y", "|", "j", "o", "e")  val c = groupstream(a)(_ == "|")(_.mkstring)  c.take(10).tolist //  list[string] = list("", adam, john, mary, joe, "", "", "", "", "") 

using implicit version:

val c = groupstream(a)(_ == "|")(_.mkstring) 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -