What causes a type error like this in Haskell?

前端 未结 1 761
自闭症患者
自闭症患者 2021-01-28 02:34

I\'m playing with Haskell to evaluate simple limits with tables of values. I have the following function defined:

f :: (Integral a) => a -> a
f x = div 1          


        
相关标签:
1条回答
  • 2021-01-28 02:42

    I think you just tried the wrong division - you really want (/) not div...

    your problem is that div which demands an Integral type (for example an Integer):

    Prelude> :t div
    div :: Integral a => a -> a -> a
    

    but then you use it with a Fractional (6.10, ...) by maping it over your leftSide and rightSide

    now GHCi defaults this to Double - but Double is not an instance of Integral - this is exactly what Haskell is complaining about.


    the thing you tried does not work and I guess you wanted to write (Integral a, Double a) => ... but in the end (if it would work - it does not since Double is type and not a type-class) it would be the same as saying f :: Double -> Double anyway - which would get you the error again (as there is no div for Double)

    To make it short: use (/) instead of div and it should work:

    f :: Fractional r => r -> r
    f x = (1 /) $ subtract 6 x
    

    here is your first example:

    Prelude> let leftSide = [5.90, 5.91..5.99]
    Prelude> map f leftSide
    [-10.000000000000036,-11.111111111111128
    ,-12.49999999999999,-14.285714285714228
    ,-16.66666666666653,-19.999999999999716
    ,-24.999999999999424,-33.33333333333207
    ,-49.999999999996625,-99.99999999998437]
    

    btw: you can make this shorter if you use point-free:

    f = (1 /) . (6 -)
    

    or a bit cleaner / more readable if you write it out

    f x = 1 / (6 - x)
    
    0 讨论(0)
提交回复
热议问题