scala - What's the idiomatic way to map producing 0 or 1 results per entry? -


what's idiomatic way call map on collection producing 0 or 1 result per entry?

suppose have:

val data = array("a", "x:y", "d:e") 

what i'd result is:

val target = array(("x", "y"), ("d", "e")) 

(drop without colon, split on colon , return tuples)

so in theory think want like:

val attempt1 = data.map( arg => {     arg.split(":", 2) match {       case array(l,r) => (l, r)       case _ => (none, none)     }   }).filter( _._1 != none ) 

what i'd avoid need any-case , rid of filter.

i pre-filtering (but have test regex twice):

val attempt2 = data.filter( arg.contains(":") ).map( arg => {       val array(l,r) = arg.split(":", 2)       (l,r)     }) 

last, use some/none , flatmap...which rid of need filter, scala programmers expect?

val attempt3 = data.flatmap( arg => {      arg.split(":", 2) match {        case array(l,r) => some((l,r))        case _ => none      } }) 

it seems me there'd idiomatic way in scala, there?

with regex extractor , collect :-)

scala> val r = "(.+):(.+)".r r: scala.util.matching.regex = (.+):(.+)  scala> array("a", "x:y", "d:e") collect {      |   case r(a, b) => (a, b)      | } res0: array[(string, string)] = array((x,y), (d,e)) 

edit:

if want map, can do:

scala> val x: map[string, string] = array("a", "x:y", "d:e").collect { case r(a, b) => (a, b) }.tomap x: map[string,string] = map(x -> y, d -> e) 

if performance concern, can use collection.breakout shown below avoid creation of intermediate array:

scala> val x: map[string, string] = array("a", "x:y", "d:e").collect { case r(a, b) => (a, b) } (collection.breakout) x: map[string,string] = map(x -> y, d -> e) 

Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -