Last active
February 4, 2016 20:16
-
-
Save vkostyukov/309d81b8a6caa80b6672 to your computer and use it in GitHub Desktop.
Dict.scala
This file contains hidden or 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
sealed trait Dict | |
object Dict { | |
// dict(“a”: “apple”, “b”: dict(“c”: “cat”, “d”: “dog”)) -> “{a:apple,b:{c:cat,d:dog}}” | |
case class Val(s: String) extends Dict | |
case class Obj(m: Map[String, Dict]) extends Dict | |
def encode(d: Dict): String = { | |
def loop(dd: Dict, sb: StringBuilder): StringBuilder = dd match { | |
case Val(s) => sb.append(s) | |
case Obj(m) => | |
sb.append("dict(") | |
m.foreach { case (k, v) => loop(v, sb.append(k).append(":")).append(",") } | |
if (m.nonEmpty) { sb.setLength(sb.length() - 1) } | |
sb.append(")") | |
} | |
loop(d, new StringBuilder).toString | |
} | |
} | |
// Exiting paste mode, now interpreting. | |
defined trait Dict | |
defined object Dict | |
scala> Dict.encode(Dict.Obj(Map("foo" -> Dict.Val("bar")))) | |
res0: String = dict(foo:bar) | |
scala> Dict.encode(Dict.Obj(Map("foo" -> Dict.Val("bar"), "baz" -> Dict.Obj(Map("ban" -> Dict.Val("rat")))))) | |
res2: String = dict(foo:bar,baz:dict(ban:rat)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment