Scala 将类型类成员身份扩展到集合

Scala 将类型类成员身份扩展到集合,scala,typeclass,Scala,Typeclass,这是我的第一个问题,所以我希望我做的每件事都是正确的 我的情况是:我想用一个typeclass来表示某些类型在函数下是封闭的。具体地说,类型类被称为Substitutable。其目的是,如果T是Substitutable的一个实例,那么您可以对其应用替换,并得到T。这是通过applySubstitution方法实现的,每个substituable实例都必须实现该方法 集合继承此闭包属性;如果我对Ts的列表应用替换元素,其中T是Substitutable的实例,那么结果将再次是Ts的列表,因此li

这是我的第一个问题,所以我希望我做的每件事都是正确的

我的情况是:我想用一个typeclass来表示某些类型在函数下是封闭的。具体地说,类型类被称为
Substitutable
。其目的是,如果
T
Substitutable
的一个实例,那么您可以对其应用替换,并得到
T
。这是通过
applySubstitution
方法实现的,每个
substituable
实例都必须实现该方法

集合继承此闭包属性;如果我对
T
s的列表应用替换元素,其中
T
Substitutable
的实例,那么结果将再次是
T
s的列表,因此
list[T]
本身就是
Substitutable
的实例

简而言之,如果
T
是一个实例,我想将
List[T]
作为
substituble
的一个实例。我看不出该如何表达这一点。在我看来,我需要写一些

implicit objectSubstitutableList[T: Substitutable] extends Substitutable[List[T]],
但这是不可能的,因为我无法为隐式对象提供类型参数


如何解决这个问题?

您需要一个隐式定义,因为List[T]的typeclass需要一个隐式参数(T的typeclass实例)

为字符串定义typeclass实例

implicit val stringIsSubstitutable: Substitutable[String] =
  new Substitutable[String] {
    def applySubstitution(value: String, f: String => String) = f(value)
  }
列表[String]的Typeclass实例自动生成

scala> implicitly[Substitutable[List[String]]]
res3: Substitutable[List[String]] = Substitutable$$anon$2@30376991
这不起作用,因为隐式作用域中没有可替换的[Int]

scala> implicitly[Substitutable[List[Int]]]
<console>:14: error: could not find implicit value for parameter e: Substitutable[List[Int]]        
scala>隐式[Substitutable[List[Int]]
:14:错误:找不到参数e的隐式值:可替换[列表[Int]]
scala> implicitly[Substitutable[List[Int]]]
<console>:14: error: could not find implicit value for parameter e: Substitutable[List[Int]]