Created
May 9, 2013 08:37
-
-
Save esuomi/5546311 to your computer and use it in GitHub Desktop.
Two lists with distinct types, both types having their unique definition of object identity. Find all id:s which exist in both lists or only in the latter.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Ident(identity:Int) { | |
def ident = identity | |
override def toString = "[id:"+identity+"]" | |
} | |
class Id(identity:Int) { | |
def id = identity | |
override def toString = "[id:"+identity+"]" | |
} | |
object diffAndDistinctOfTypes { | |
val idents = List(new Ident(1), new Ident(2), new Ident(3)) //> idents : List[Ident] = List([id:1], [id:2], [id:3]) | |
val ids = List(new Id(3), new Id(1), new Id(6)) //> ids : List[Id] = List([id:3], [id:1], [id:6]) | |
def filterLists[IdentityA, IdentityB]( | |
aList:List[IdentityA], | |
bList:List[IdentityB] | |
)(distinctEquality:(IdentityA,IdentityB) => Boolean) = { | |
aList.filter( ident => { | |
bList.filter(id => distinctEquality(ident, id)).length > 0 | |
}) | |
} | |
def inBoth = filterLists(idents, ids) {(a:Ident, b:Id) => | |
a.ident == b.id | |
}.collect { case id => | |
id.ident | |
} | |
def onlyInB = filterLists(ids, idents) {(a:Id, b:Ident) => | |
b.ident != a.id | |
}.collect { case id => | |
id.id | |
} | |
val result = inBoth ++ onlyInB distinct //> result : List[Int] = List(1, 3, 6) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment