Here is a bad solution (if you create the whole card and then discard it in order):
def uniqueMap[A,B](s: Seq[(A,B)]) = { val m = s.toMap if (m.size == s.length) Some(s) else None }
Here is a mutable failover solution (as soon as an error is detected), follow these steps:
def uniqueMap[A,B](s: Seq[(A,B)]) = { val h = new collection.mutable.HashMap[A,B] val i = s.iterator.takeWhile(x => !(h contains x._1)).foreach(h += _) if (h.size == s.length) Some(h) else None }
And here is an indisputable fault tolerant solution:
def uniqueMap[A,B](s: Seq[(A,B)]) = { def mapUniquely(i: Iterator[(A,B)], m: Map[A,B]): Option[Map[A,B]] = { if (i.hasNext) { val j = i.next if (m contains j._1) None else mapUniquely(i, m + j) } else Some(m) } mapUniquely(s.iterator, Map[A,B]()) }
Edit: and here is a solution using put for speed (hopefully):
def uniqueMap[A,B](s: Seq[(A,B)]) = { val h = new collection.mutable.HashMap[A,B] val okay = s.iterator.forall(x => { val y = (h put (x._1,x._2)) y.isEmpty || y.get == x._2 }) if (okay) Some(h) else None }
Edit: now checked, and this is ~ 2x as fast at the input, which works (returns true) than Moritz 'or my direct solution.