haskell - 如何纠正这个haskell对数函数?

标签 haskell functional-programming

natlog x = until cond count (1,1,0)
    where 
        cond (_,val,_) = val < 0.001
        count (i,val,sum) = (i+1,(-x)^i/i,sum+val)

此函数尝试计算 log 1 + x

问题类似于What is the type signature of this Haskell function? .

错误代码:

<interactive>:1:8:
    Ambiguous type variable `t0' in the constraints:
      (Num t0) arising from the literal `1' at <interactive>:1:8
      (Integral t0) arising from a use of `natlog' at <interactive>:1:1-6
      (Fractional t0) arising from a use of `natlog'
                      at <interactive>:1:1-6
    Probable fix: add a type signature that fixes these type variable(s)
    In the first argument of `natlog', namely `1'
    In the expression: natlog 1
    In an equation for `it': it = natlog 1

最佳答案

问题是,由于 ^,您的输入需要是 Integral,由于 /,您的输入需要是 Fractional >。您可以通过对其中之一使用不同的运算符来轻松解决此问题;例如,使用 ** 而不是 ^:

natlog x = until cond count (1,1,0)
    where 
        cond (_,val,_) = val < 0.001
        count (i,val,sum) = (i+1,(-x)**i/i,sum+val)

关于haskell - 如何纠正这个haskell对数函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8868111/

相关文章:

haskell - 什么是 Haskell 中的组合器

haskell - 用于交换函数参数的函数类型

c# - 等待来自 Language-ext 的 OptionAsync<T>

javascript - 映射添加/减少具有相同索引的两个数组对象

java - 为 kotlin 尝试 monad

haskell - 如何在没有安装 cabal 或 ghc 的情况下运行 haskell 可执行文件(cabal 项目)

haskell - monads Writer m 和 Either e 是绝对对偶的吗?

haskell - 在Haskell中,如何将整数转换为代理(n::KnownNat),其中n等于整数?

function - Haskell 中的折叠实现

haskell - 递归到 Haskell 中尚不存在的函数