chisel - 凿子: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.UInt
to Int
)?
解决方案
我认为你不能那样做。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 才能输出值;)
推荐阅读
- linux - 在 ubuntu 上查找文件
- docker - 我可以在 Dockerfile 中结合 COPY 指令来最小化镜像层的数量吗?
- sql - 尝试制作Reddit的ER图
- javascript - Javascript 秒表希望时钟元素成为 div 而不是输入
- jsf - 如何从 JSF 中的视图列表中获取列?
- core-data - 带有Core Data的SwiftUI在Xcode 12的模拟器中获得黑屏
- flutter - 如何在 Flutter 中添加装饰 DropdownButton
- c# - 如何在 WPF 用户控件中的整个 Grid LeftClick 上绑定命令
- node.js - Nodemailer 无法使用本地 smtp 服务器
- javascript - 如何禁用下个月和下个月以及如何禁用某些日子(灰色)?