flatronka
flatronka

Reputation: 1081

How to correct this haskell logarithm function?

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)

This function a try to count log 1 + x

The problem is similar to What is the type signature of this Haskell function? .

Error code:

<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

Upvotes: 2

Views: 593

Answers (1)

Tikhon Jelvis
Tikhon Jelvis

Reputation: 68152

The issue is that your input needs to be an Integral because of ^ and a Fractional because of /. You can easily fix this by using a different operator for one of these; for example, use ** instead of ^:

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)

Upvotes: 4

Related Questions