merge 2 lists A over B in scala -



merge 2 lists A over B in scala -

i have 2 immutable case classes a(source, key, value) , b(source, key, value) want add together on b in such way when 'source' , 'key' doesn't exist, added b , when 'source' , 'key' exist replace value b 1 a. same way 'merge_array' function php works on multidimensional array.

i tried 'a.union(b).groupby(.key)' , 'groupby(.source)' , 1st value. realized can never sure first value value of a.

i'm quite new scala , ran out of ideas how functional immutable point of view.

anyone has thought how this?

thank you

edit:

case class translationvalue(source: string, key: string, value: string) def main(args:array[string]):unit = { println(merge(data1.toset, data2.toset)) } def merge(a: set[translationvalue], b: set[translationvalue]) = { a.union(b).groupby(_.key).flatmap{ case (s, v) => v.groupby(_.source).flatmap{case (s1, v1) => { (res <- 0 0) yield v1.head } } } }

example

data1 has info

set( translationvalue(messages,no,no), translationvalue(messages,ordref,order reference), translationvalue(messages,ordid,order id) )

data2 has data

set( translationvalue(messages,no,no), translationvalue(messages,ordref,orderref) translationvalue(messages,name,name) )

putting data1 on data2 want obtain

list( translationvalue(messages,no,no), translationvalue(messages,ordref,order reference), translationvalue(messages,ordid,order id) translationvalue(messages,name,name) )

i know can done better, said, i'm learning :)

you can grouping in 1 go:

def merge(a: seq[translationvalue], b: seq[translationvalue]) = { a.union(b).groupby(t=>(t.key,t.source)).map(c=>c._2.head) }

i think override equals method translationvalue 2 translation values equal when source , key same(the hashcode method has overridden). a.union(b) enough.

edit: seems set doesnt guarantee order of items(scala: can rely on order of items in set?), seq should.

list scala merge immutability

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -