algorithm - Scala - sort based on Future result predicate -
i have array of objects want sort, predicate sorting asynchronous. scala have either standard or 3rd party library function sorting based on predicate type signature of (t, t) -> future[bool] rather (t, t) -> bool?
alternatively, there other way structure code? i've considered finding 2-pair permutations of list elements, running predicate on each pair , storing result in map((t, t), bool) or structure effect, , sorting on - suspect have many more comparisons executed naive sorting algorithm would.
if predicate async may prefer async result , avoid blocking threads using await
if want sort list[(t,t)] according future boolean predicate, easiest sort list[(t,t,boolean)]
so given have list[(t,t)] , predicate (t, t) -> future[bool], how can list[(t,t,boolean)]? or rather future[list[(t,t,boolean)]] want keep async behavior.
val list: list[(t,t)] = ... val predicate = ... val listoffutures: list[future[(t,t,boolean]] = list.map { tuple2 => predicate(tuple2).map( bool => (tuple2._1, tuple2._2, bool) } val futurelist: future[list[(t,t,boolean)]] = future.sequence(listoffutures) val futuresortedresult: future[list[(t,t)]] = futurelist.map { list => list.sort(_._3).map(tuple3 => (tuple3._1,tuple3._2)) } this pseudo-code, didn't compile , may not, idea.
the key future.sequence, useful, somehow permits transform monad1[monad2[x]] monad2[monad1[x]] notice if of predicate future fail, global sort operation failure.
if want better performance may better solution "batch" call service returning future[boolean]. example instead of (t, t) -> future[bool] maybe can design service (if own obviously) list[(t, t)] -> future[list[(t,t,bool)] can need in async single call.
Comments
Post a Comment