Higher Grade Types for Multisets

I would like to write a class Multiset[T, S[_]]in Scala that accepts 2 type parameters: T- this is the type of the element, while it Sis the base representation of the set. In this multiset, an instance is built S[(T, Int)](each pair Thas an element, and Intits number of occurrences). This is possible in C ++:

template<typename T, template<typename> S>

Two questions:

  • How to declare a restriction on Swhat it should be a set? Does it work Multiset[T, S[_] <: Set[_]]?

  • Is it possible to declare a restriction that an instance S[(T, Int)]can be created? This can be done in C # using a constraint where S: new().

+4
source share
1 answer

. S[X] <: Set[X]. , , . . , S[X] <: Set[List[X]].

: , #, , , , . , , - . Func<S> , factory, new ,

class Generic<T> 
{
   public Generic(..., Func<T> factory)
}

static class Generic 
{
  public Generic<T> Create(....) where T : new {
    return new Generic(..., () => new T());
  }
}

scala . , .

trait Builder[A] {
   def build(): A
}

object Builder {
  def build[A: Builder] : A = implicitly[Builder[A]].build()
}

class Generic[A: Builder](....) {....
    ...
    // instead of val a = new A()
    val a = Builder.build[A]
    ....
}

, , . , , .

+3

All Articles