mattomatic
mattomatic

Reputation: 51

scala custom map

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)

Upvotes: 5

Views: 2033

Answers (4)

Faiz
Faiz

Reputation: 16245

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.

Upvotes: 6

Kristian Domagala
Kristian Domagala

Reputation: 3696

The way it's written, there's no way to enforce that it can't be both a Map and a String at the same time. I would be looking at capturing the value using Either and adding whatever convenience methods you require:

case class Chunk(value:Either[Map[String,Chunk],String]) {
  ...
}

That will also force you to think about what you really need to do in situations such as adding a key/value pair to a Chunk that represents a String.

Upvotes: 2

xiefei
xiefei

Reputation: 6599

def +(kv: (String, Chunk)):Chunk = new Chunk(_map + kv, _value)
override def +[B1 >: Chunk](kv: (String, B1)) = _map + kv

What you need is a new + method, and also implement the one declared in Map trait.

Upvotes: 1

Ryan LeCompte
Ryan LeCompte

Reputation: 4321

Have you considered using composition instead of inheritance? So, instead of Chunk extending Map[String, Chunk] directly, just have Chunk internally keep an instance of Map[String, Chunk] and provide the extra methods that you need, and otherwise delegating to the internal map's methods.

Upvotes: 1

Related Questions