gpt4 book ai didi

haskell - 无法构造无限类型 - 实现尾递归阶乘计算器

转载 作者:行者123 更新时间:2023-12-04 18:26:00 32 4
gpt4 key购买 nike

我正在尝试实现阶乘的尾递归版本:

let{factorial 0 n = n; factorial x n =  factorial (x-1, n * x)}

我明白了:

<interactive>:1:41:
Occurs check: cannot construct the infinite type: t1 = t1 -> t1
In the return type of a call of `factorial'
In the expression: factorial (x - 1, n * x)
In an equation for `factorial':
factorial x n = factorial (x - 1, n * x)

<interactive>:1:52:
Occurs check: cannot construct the infinite type: t0 = (t0, t1)
In the first argument of `(-)', namely `x'
In the expression: x - 1
In the first argument of `factorial', namely `(x - 1, n * x)'

<interactive>:1:61:
Occurs check: cannot construct the infinite type: t1 = (t0, t1)
In the second argument of `(*)', namely `x'
In the expression: n * x
In the first argument of `factorial', namely `(x - 1, n * x)'

我如何在这里构建无限类型? (使用 GHCi 7.0.1)

最佳答案

我不是一个强大的 Haskell 程序员,但我认为你想重写

factorial x n =  factorial (x-1, n * x)

作为

factorial x n =  factorial (x-1) (n * x)

因为 (x-1, n * x) 是一个对类型,这不是你想要的。

希望这对您有所帮助!

关于haskell - 无法构造无限类型 - 实现尾递归阶乘计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11638061/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com