Reputation: 191
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.
Upvotes: 1
Views: 73
Reputation: 152697
Give epsilon
a suitably polymorphic type signature:
epsilon :: Fractional a => a
You may also like the explanations in What is the monomorphism restriction?.
Upvotes: 6