Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala custom map

Tags:

types

scala

I'm trying to implement a new type, Chunk, that is similar to a Map. Basically, a "Chunk" is either a mapping from String -> Chunk, or a string itself.

Eg it should be able to work like this:

val m = new Chunk("some sort of value") // value chunk 
assert(m.getValue == "some sort of value")

val n = new Chunk("key" -> new Chunk("value"), // nested chunks
                  "key2" -> new Chunk("value2"))
assert(n("key").getValue == "value")
assert(n("key2").getValue == "value2")

I have this mostly working, except that I am a little confused by how the + operator works for immutable maps.

Here is what I have now:

class Chunk(_map: Map[String, Chunk], _value: Option[String]) extends Map[String, Chunk] {
  def this(items: (String, Chunk)*) = this(items.toMap, None)
  def this(k: String) = this(new HashMap[String, Chunk], Option(k))
  def this(m: Map[String, Chunk]) = this(m, None)

  def +[B1 >: Chunk](kv: (String, B1)) = throw new Exception(":( do not know how to make this work")
  def -(k: String) = new Chunk(_map - k, _value)
  def get(k: String) = _map.get(k)
  def iterator = _map.iterator

  def getValue = _value.get
  def hasValue = _value.isDefined

  override def toString() = {
    if (hasValue) getValue
    else "Chunk(" + (for ((k, v) <- this) yield k + " -> " + v.toString).mkString(", ") + ")"
  }

  def serialize: String = {
    if (hasValue) getValue
    else "{" + (for ((k, v) <- this) yield k + "=" + v.serialize).mkString("|") + "}"
  }
}

object main extends App {
  val m = new Chunk("message_info" -> new Chunk("message_type" -> new Chunk("boom")))
  val n = m + ("c" -> new Chunk("boom2"))
}

Also, comments on whether in general this implementation is appropriate would be appreciated.

Thanks!

Edit: The algebraic data types solution is excellent, but there remains one issue.

def +[B1 >: Chunk](kv: (String, B1)) = Chunk(m + kv) // compiler hates this
def -(k: String) = Chunk(m - k) // compiler is pretty satisfied with this

The - operator here seems to work, but the + operator really wants me to return something of type B1 (I think)? It fails with the following issue:

overloaded method value apply with alternatives: (map: Map[String,Chunk])MapChunk <and> (elems: (String, Chunk)*)MapChunk cannot be applied to (scala.collection.immutable.Map[String,B1])

Edit2: Xiefei answered this question -- extending map requires that I handle + with a supertype (B1) of Chunk, so in order to do this I have to have some implementation for that, so this will suffice:

def +[B1 >: Chunk](kv: (String, B1)) = m + kv

However, I don't ever really intend to use that one, instead, I will also include my implementation that returns a chunk as follows:

def +(kv: (String, Chunk)):Chunk = Chunk(m + kv)
like image 754
mattomatic Avatar asked Nov 28 '12 04:11

mattomatic


1 Answers

How about an Algebraic data type approach?

  abstract sealed class Chunk
  case class MChunk(elems: (String, Chunk)*) extends Chunk with Map[String,Chunk] {
    val m = Map[String, Chunk](elems:_*)
    def +[B1 >: Chunk](kv: (String, B1)) =  m + kv
    def -(k: String) =  m - k
    def iterator = m.iterator
    def get(s: String) = m.get(s)
  }
  case class SChunk(s: String) extends Chunk
  // A 'Companion' object that provides 'constructors' and extractors..
  object Chunk {
    def apply(s: String) = SChunk(s)
    def apply(elems: (String, Chunk)*) = MChunk(elems: _*)
    // just a couple of ideas...
    def unapply(sc: SChunk) = Option(sc).map(_.value)
    def unapply(smc: (String, MChunk)) = smc match {
      case (s, mc) => mc.get(s)
    }

  }

Which you can use like:

val simpleChunk = Chunk("a")
val nestedChunk = Chunk("b" -> Chunk("B"))
// Use extractors to get the values.
val Chunk(s) = simpleChunk // s will be the String "a"
val Chunk(c) = ("b" -> nestedChunk) // c will be a Chunk: Chunk("B")
val Chunk(c) = ("x" -> nestedChunk) // will throw a match error, because there's no "x"
// pattern matching:
("x" -> mc) match { 
  case Chunk(w) => Some(w)
  case _ => None 
} 

The unapply extractors are just a suggestion; hopefully you can mess with this idea till you get what you want.

like image 195
Faiz Avatar answered Oct 13 '22 18:10

Faiz