【问题标题】:How to correct this haskell logarithm function?如何纠正这个haskell对数函数?
【发布时间】:2012-01-15 15:18:15
【问题描述】:
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

【问题讨论】:

    标签: haskell functional-programming


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      • 2016-08-13
      • 1970-01-01
      相关资源
      最近更新 更多