3
quadraticRoots :: Floating t => t -> t -> t -> (t, t)
quadraticRoots a b c = if d < 0 then error "0" else (x, y)
                          where
                            x = e + sqrt d / (2 * a)
                            y = e - sqrt d / (2 * a)
                            d = b * b - 4 * a * c
                            e = - b / (2 * a)

The above code gives the following error in Hugs:

Cannot justify constraints in explicitly typed binding
*** Expression    : quadraticRoots
*** Type          : Floating a => a -> a -> a -> (a,a)
*** Given context : Floating a
*** Constraints   : Ord a

Can anyone help me interpret this?

2 Answers 2

4

In order to make a comparison like d < 0, the thing you are comparing must be a member of the Ord typeclass. Thus, we need to amend our type signature to include the additional constraint Ord:

quadraticRoots :: (Ord t, Floating t) => t -> t -> t -> (t, t)
Sign up to request clarification or add additional context in comments.

Comments

1

Your type signature says t is in Floating type class, but compiler found it must also be in Ord.

Were Ord a superclass of Floating, all would be good. But it's not.

To see the type the compiler derives (infers), just omit the explicit type signature. Then, after defining the function in GHCi, ask

~> :t quadraticRoots
quadraticRoots :: (Ord t, Floating t) => t -> t -> t -> (t, t)

< is in Ord, sqrt is in Floating, and / is in Fractional. But Floating is a subclass of Fractional, so specifying it alone is enough for the both of them:

~> :i sqrt
class Fractional a => Floating a where
  ...
  sqrt :: a -> a
  ...

~> :i /
class Num a => Fractional a where
  (/) :: a -> a -> a
  ...
infixl 7 /

~> :i <
class Eq a => Ord a where
  ...
  (<) :: a -> a -> Bool
  ...
infix 4 <

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.