1

I am trying to define a function that requires me to add a fractional type to a double but I seem to receive an error.

epsilon = 0.0000001
dif :: (Fractional a) => (a->a) -> a -> a

dif f x = (f(x+epsilon)-f(x))/epsilon

Haskell seems to be having trouble interpreting x+epsilon but this seems odd considering that x is defined to be a Fractional type in the function declaration and epsilon is a double (which is a part of the Fractional type class?

Heres the error I get:

Couldn't match expected type ‘a’ with actual type ‘Double’
  ‘a’ is a rigid type variable bound by
      the type signature for dif :: Fractional a => (a -> a) -> a -> a
      at dif.hs:3:8
Relevant bindings include
  x :: a (bound at dif.hs:5:7)
  f :: a -> a (bound at dif.hs:5:5)
  dif :: (a -> a) -> a -> a (bound at dif.hs:5:1)
In the second argument of ‘(+)’, namely ‘epsilon’
In the first argument of ‘f’, namely ‘(x + epsilon)’

Thank you.

orange_juice
  • 191
  • 1
  • 11

1 Answers1

6

Give epsilon a suitably polymorphic type signature:

epsilon :: Fractional a => a

You may also like the explanations in What is the monomorphism restriction?.

Community
  • 1
  • 1
Daniel Wagner
  • 145,880
  • 9
  • 220
  • 380
  • In particular, `epsilon` is a Double, so `dif` will work only with `a ~ Double`. However, the type signature promises to work for *any* `Fractional a`, and the compiler is noting that your implementation doesn't live up to this promise, because it depends on `dif`. – amalloy Jun 27 '16 at 20:39