Note that there are some explanatory texts on larger screens.

plurals
  1. POAutomatically Hash Consed Case Classes
    primarykey
    data
    text
    <p>I'm looking for a way to have classes that behave just like case classes, but that are automatically <a href="http://en.wikipedia.org/wiki/Hash_consing" rel="noreferrer">hash consed</a>.</p> <p>One way to achieve this for integer lists would be:</p> <pre><code>import scala.collection.mutable.{Map=&gt;MutableMap} sealed abstract class List class Cons(val head: Int, val tail: List) extends List case object Nil extends List object Cons { val cache : MutableMap[(Int,List),Cons] = MutableMap.empty def apply(head : Int, tail : List) = cache.getOrElse((head,tail), { val newCons = new Cons(head, tail) cache((head,tail)) = newCons newCons }) def unapply(lst : List) : Option[(Int,List)] = { if (lst != null &amp;&amp; lst.isInstanceOf[Cons]) { val asCons = lst.asInstanceOf[Cons] Some((asCons.head, asCons.tail)) } else None } } </code></pre> <p>And, for instance, while </p> <pre><code>scala&gt; (5 :: 4 :: scala.Nil) eq (5 :: 4 :: scala.Nil) resN: Boolean = false </code></pre> <p>we get</p> <pre><code>scala&gt; Cons(5, Cons(4, Nil)) eq Cons(5, Cons(4, Nil)) resN: Boolean = true </code></pre> <p>Now what I'm looking for is a <em>generic</em> way to achieve this (or something very similar). Ideally, I don't want to have to type much more than:</p> <pre><code>class Cons(val head : Int, val tail : List) extends List with HashConsed2[Int,List] </code></pre> <p>(or similar). Can someone come up with some type system voodoo to help me, or will I have to wait for the macro language to be available?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload