Last active
August 29, 2015 13:57
-
-
Save inanna-malick/9817552 to your computer and use it in GitHub Desktop.
Scala Trie
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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