package hu.bme.mit.inf.dslreasoner.util import java.util.HashSet import java.util.LinkedList import java.util.List import java.util.Map import java.util.Set import org.eclipse.xtext.xbase.lib.Functions.Function1 import java.util.HashMap import java.util.LinkedHashMap import org.eclipse.emf.ecore.EObject class CollectionsUtil { public def static TO lookup(FROM from, Map map) { if(map.containsKey(from)) { return map.get(from) } else { val proxys = map.values.filter(EObject).filter[it.eIsProxy] var message = ''' The map does not contains the key "«from.toString»"! --- Elements: --- «FOR entry : map.entrySet SEPARATOR '\n'»«entry.key» -> «entry.value»«ENDFOR» -----------------''' if(!proxys.empty) { message = ''' The map contains Proxy objects: «proxys.toList» «message» ''' } throw new IllegalArgumentException(message); } } public def TO ifThenElse(FROM source, Function1 condition, Function1 ifTrue, Function1 ifFalse) { if(condition.apply(source)) { return ifTrue.apply(source) } else { return ifFalse.apply(source) } } public def static Union(Map a, Map b) { (a.keySet + b.keySet).toInvertedMap[key | if(a.containsKey(key)) a.get(key) else b.get(key) ] } public def static putOrAddToSet(Map> map, Key key, Value value) { if(map.containsKey(key)) { map.get(key).add(value) }else{ val set = new HashSet() => [it.add(value)] map.put(key, set) } } public def static putOrAddToList(Map> map, Key key, Value value) { if(map.containsKey(key)) { map.get(key).add(value) }else{ val set = new LinkedList() => [it.add(value)] map.put(key, set) } } def public static Map copyMap(Map oldMap, Iterable newValues, Function1 indexExtractor) { val Map valueIndexes = newValues.toMap[to|indexExtractor.apply(to)]; val res = oldMap.mapValues[value | indexExtractor.apply(value).lookup(valueIndexes)] // println('''from:''') // newValues.forEach[println(it)] // println('''old:''') // oldMap.values.forEach[println(it)] // println('''new:''') // res.values.forEach[println(it)] return res } def public static Map bijectiveInverse(Map m) { m.keySet.toMap[x|x.lookup(m)] } def public static Map> inverse(Map m) { val res = new LinkedHashMap> m.entrySet.forEach[res.putOrAddToList(it.value,it.key)] return res } def public static List transitiveClosurePlus(Type source, Function1> next) { val res = new LinkedList() transitiveClosureHelper(res,source,next) return res } def public static List transitiveClosureStar(Type source, Function1> next) { val res = new LinkedList() res += source transitiveClosureHelper(res,source,next) return res } def private static void transitiveClosureHelper(List result, Type actual, Function1> next) { val front = next.apply(actual) for(elementInFront : front) { result += elementInFront transitiveClosureHelper(result,elementInFront,next) } } }