【问题标题】:Another subtype after a type bound in scala在 scala 中绑定的类型之后的另一个子类型
【发布时间】:2021-08-14 03:18:32
【问题描述】:

class PEControl[T <: Data : Arithmetic](accType: T),这是来自 riscv-gemmini 的类定义。 Data 类型是 chisel 中的基本数据类型,Arithmetic 提供了对 Dataabstract class Arithmetic[T <: Data] 的一些算术运算。

<: Type : Type 使用的语法是什么,这是什么意思? 我发现语法从here 被称为TypeParamBounds ::= TypeBounds {‘:’ Type}。我在哪里可以得到一些关于它的详细信息,谢谢。

【问题讨论】:

标签: scala chisel context-bound


【解决方案1】:

<: type :>

Scala 结合了面向对象的概念和函数式编程概念。例如,在 Scala 中,可以使用子类型约束和类型类约束来约束类型参数

T <: Data                // subtyping contraint on T
T : Arithmetic           // type class constraint on T
T <: Data : Arithmetic   // subtyping and type class contraint on T

在这两种情况下,这些编译时约束的重点是告诉编译器类型参数T 提供了哪些功能,也就是说,我们可以对T 类型的值调用哪些方法。决定对类型参数施加什么样的约束是一项设计决策。一些程序员喜欢带有类型类的参数多态的纯函数式编程方法,其他人更喜欢更面向对象的子类型方法,还有一些人认为我们仍然没有探索 Scala 提供的混合方法的真正力量。无论哪种方式,Scala 都不会为您做出决定。附带说明一下,在某些语言(例如 Rust)中,不鼓励或完全删除子类型多态性。

【讨论】:

    【解决方案2】:

    类型边界是以下的简写:

    class PEControl[T <: Data : Arithmetic](accType: T)
    
    // equivalent to
    
    class PEControl[T <: Data](accType: T)(implicit noName: Arithmetic[T])
    
    // which means in both cases in the body of your class 
    // you can summon instances of arithmetic for all Ts
    
    class PEControl[T <: Data : Arithmetic](accType: T) {
    
      def doSomethingWithT(t1: T, t2: T): Unit = {
        implicitly[Arithmetic[T]].plus(t1, t2)
      }
    
    }
    

    【讨论】:

      【解决方案3】:

      Mario 的回答很好地讨论了不同类型的多态性,SimY4 的回答展示了如何通过隐式在 Scala 中实现类型类的机械细节。

      Chisel 3.5(尚未发布)引入了一个名为DataView 的新功能,它是使用类型类实现的。 In the documentation for DataView 我试图提供一个简短的文档来介绍类型类以及它们为何有用。希望该文档也能帮助解释!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-12
        • 1970-01-01
        • 2015-06-05
        • 2015-10-20
        • 1970-01-01
        • 1970-01-01
        • 2019-08-31
        • 1970-01-01
        相关资源
        最近更新 更多