【发布时间】:2020-07-08 00:15:10
【问题描述】:
我想实现以下函数来计算 Julia 中整数 $n$ 的 $(-1)^n / (2n + 1)$ 到 Haskell 中。
# Julia
powersign(n) = ifelse(n % 2 == 0, 1, -1)
leibniz_term(n) = powersign(n) / (2n + 1)
println(leibniz_term(10)) # 0.047619047619047616
我写
-- Haskell
powersign 0 = 1
powersign 1 = -1
powersign n = powersign (rem n 2)
leibniz_term n = (powersign n) / (2 * n + 1)
main = print (leibniz_term 10)
但这会产生以下错误。
$ ghc -o leibniz_hs leibniz.hs
[1 of 1] Compiling Main ( leibniz.hs, leibniz.o )
leibniz.hs:9:8: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘print’
prevents the constraint ‘(Show a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance Show Ordering -- Defined in ‘GHC.Show’
instance Show Integer -- Defined in ‘GHC.Show’
instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’
...plus 22 others
...plus 13 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the expression: print (leibniz_term 10)
In an equation for ‘main’: main = print (leibniz_term 10)
|
9 | main = print (leibniz_term 10)
| ^^^^^^^^^^^^^^^^^^^^^^^
...
可能,我需要在某处添加类型注释,但我不知道该怎么做。 如何修改代码才能正常工作?
【问题讨论】:
-
建议为每个定义提供一个类型签名——这将产生更好的错误消息。另外,打开警告,并尽量尊重它们。
标签: haskell