Advertisement
Guest User

CountingTrie Attempt

a guest
Jan 8th, 2015
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.92 KB | None | 0 0
  1. package org.gdget.util
  2.  
  3. import scala.collection.{immutable, mutable}
  4.  
  5. /** Description of Class
  6.   *
  7.   * @author hugofirth
  8.   */
  9. class CountingTrie[A] extends mutable.Map[IndexedSeq[A],Long] with mutable.MapLike[IndexedSeq[A],Long, CountingTrie[A]]{
  10.   type TokenString = IndexedSeq[A]
  11.  
  12.  
  13.   var suffixes: immutable.Map[A,CountingTrie[A]] = Map.empty
  14.   var value: Option[Long] = None
  15.   var total: Long = 0L
  16.  
  17.   def withPrefix(prefix: TokenString): CountingTrie[A] = {
  18.     if (prefix.isEmpty) this
  19.     else {
  20.       val leading = prefix(0)
  21.       suffixes get leading match {
  22.         case None =>
  23.           suffixes = suffixes + (leading -> empty)
  24.         case _ =>
  25.       }
  26.       suffixes(leading) withPrefix (prefix takeRight prefix.size-1)
  27.     }
  28.   }
  29.  
  30.   override def get(key: TokenString): Option[Long] = {
  31.     if(key.isEmpty) value else suffixes get key(0) flatMap( _.get(key takeRight key.size-1) )
  32.   }
  33.  
  34.   override def update(key: TokenString, value: Long):Unit = withPrefix(key).value = Some(value)
  35.  
  36.   override def remove(key: TokenString): Option[Long] = {
  37.     if(key.isEmpty) {
  38.       val previous = value; value = None; previous
  39.     } else {
  40.       suffixes get key(0) flatMap( _.remove(key takeRight key.size-1) )
  41.     }
  42.   }
  43.  
  44.   override def +=(kv: (TokenString, Long)): CountingTrie[A] = { update(kv._1, kv._2); this }
  45.  
  46.   override def -=(key: TokenString): CountingTrie[A] = { remove(key); this }
  47.  
  48.   override def iterator: Iterator[(TokenString, Long)] = {
  49.     (for(v <- value.iterator) yield (IndexedSeq.empty[A], v)) ++
  50.       (for {
  51.         (chr,m) <- suffixes.iterator
  52.         (ts, v) <- m.iterator
  53.       } yield (chr +: ts, v))
  54.   }
  55.  
  56.   override def empty = new CountingTrie[A]
  57.  
  58. }
  59.  
  60. object CountingTrie {
  61.   def apply[A](tokens: IndexedSeq[A]*): CountingTrie[A] = {
  62.     val trie = new CountingTrie[A]; tokens foreach { tokenString: IndexedSeq[A] =>
  63.       trie += ((tokenString, 0L))
  64.     }
  65.     trie
  66.   }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement