首页 > 解决方案 > 凿子:When-otherwise 子句在函数定义中不起作用

问题描述

我正在尝试使用 Chisel 3 开发一个简单的电路来生成数字n的阶乘。这是我的实现:

class Factorial extends Module{
    val io = IO(new Bundle{
        val input = Input(UInt(8.W))
        val output = Output(UInt(16.W))
    })

    def factorial(n: UInt): UInt = { 
        when (n === 0.U) {1.U}
        .otherwise {n*factorial(n-1.U)}
    }

    io.out := factorial(io.in)
}

但是,当我尝试运行它时,出现以下错误:

cmd26.sc:9: type mismatch;
found   : Unit
required: chisel3.UInt
       .otherwise {n*factorial(n-1.U)}
                  ^Compilation Failed

这有什么特别的原因吗?我该如何解决这个问题?

另外,我意识到一个简单的解决方案是将数字n设为 type Int,并改为使用 if-else 子句。有什么方法可以对函数调用期间传递的参数进行类型转换(即 from chisel3.UIntto Int)?

标签: chisel

解决方案


我认为你不能那样做。when(){}.otherwise{} 是一种硬件结构,不返回任何值(单位),正如我们在代码中看到的那样

使用这种结构,您想“即时”生成硬件,这是不可能的。

我认为您已经像它一样直接生成了所有解决方案:

class Factorial extends Module{
    val io = IO(new Bundle{
        val input = Input(UInt(8.W))
        val output = Output(UInt(1676.W))
    })

    def factorial(n: BigInt): BigInt = {
      if(n == 0){
        1
      }else{
        n*factorial(n-1)
      }
    }

    io.output := 0.U
    for(i <- 0 to 0xFF) {
      when(io.input === i.U){
        io.output := factorial(i).U
      }
    }
}

您可以保留递归 scala 函数,但仅用于硬件生成步骤。注意255!是一个非常大的数字,您需要超过 16 位 UInt 才能输出值;)


推荐阅读