【问题标题】:Scala: Higher-kinded type as a type parameterScala:作为类型参数的高级类型
【发布时间】:2013-05-24 16:19:15
【问题描述】:

请考虑以下代码 sn-p(它演示了我实际问题的简化版本):

trait Id[Type[_]] {
  def id[S]: S => Type[S]
}

trait IdTransformer[Type[_]] {
  type Result[_]  // depends of Type
  def idTransform[P]: P => Result[P]
  def composeWith[Other[_]](other: Id[Other]) = new Id[Result[Other]] { def id[S] = x => idTransform(other.id(x)) }
}

// instance example
class OptionIdTransformer extends IdTransformer[Option] {
  type Result = Option[_]
  def idTransform[S] = x => Some(x)
}

我有 Id trait 定义了一个将值包装到类型中的函数,而 IdTransformer trait 定义了一种向 id 操作添加新逻辑的方法。我想以这样的方式使用它们

Transformer1.composeWith(Transformer2.composeWith(...(idInstance)))

但是当我编译代码时,我会收到错误消息

type Other takes type parameters

IdTransformer.this.Result[<error>] takes no type parameters, expected: one 

在 composeWith 方法中,虽然 Result[Other] 应该是更高种类的类型并且应该采用单个类型参数。

请说明错误的原因以及是否有解决方法。

【问题讨论】:

    标签: scala type-systems higher-kinded-types


    【解决方案1】:

    您正在尝试将一个高级类型与其他两个高级类型组合在一起。这个技巧需要什么type lambda

    trait IdTransformer[Type[_]] {
      type Result[_]  // depends of Type
      def idTransform[P]: P => Result[P]
      def composeWith[Other[_]](other: Id[Other]) = new Id[({type λ[α] = Result[Other[α]]})#λ] { def id[S] = x => idTransform(other.id(x)) }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 2023-03-30
      • 2013-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多