Skip to content

Instantly share code, notes, and snippets.

@inanna-malick
Last active August 29, 2015 13:57
Show Gist options
  • Save inanna-malick/9817552 to your computer and use it in GitHub Desktop.
Save inanna-malick/9817552 to your computer and use it in GitHub Desktop.
Scala Trie
case class Trie(v: Option[String], m: Map[Char, Trie])
def addInner(t: Trie, s: List[Char], p: String): Trie = s match {
case c::cs => Trie(t.v, t.m.updated(c, addInner(t.m.getOrElse(c, Trie(Some(p + c), Map.empty)), cs, p + c) ))
case Nil => t
}
def add(t: Trie, s: String): Trie = addInner(t, s.toList, "")
def findInner(t: Trie, s: List[Char]): Option[String] = s match {
case Nil => t.v
case c::cs => t.m.get(c).flatMap{ t => findInner(t, cs) }
}
def find(t: Trie, s: String): Option[String] = findInner(t, s.toList)
val root = Trie(None, Map.empty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment