1

For the distance between two Points, without changing the function declaration, I keep getting this error "Couldn't match expected type ‘b’ with actual type ‘a’ ‘a’ is a rigid type variable bound by the type signature for:"

type Point a = (a,a)
distance :: (Real a, Floating b) => Point a -> Point a -> b
distance (x1,y1) (x2,y2) = sqrt ((dx * dx) + (dy * dy))
  where dx = x2 - x1
    dy = y2 - y1
1
  • have you tried applying realToFrac to the result of sqrt? Commented Mar 17, 2017 at 12:34

2 Answers 2

2

sqrt returns the same type as its argument:

Prelude> :t sqrt
sqrt :: Floating a => a -> a

Since you're providing b as argument to sqrt, Haskell deduces that the return type must be b and not a.

Is there a specific reason why you cannot use

distance :: Floating b => Point b -> Point b -> b
distance (x1,y1) (x2,y2) = sqrt ((dx * dx) + (dy * dy))
  where dx = x2 - x1
        dy = y2 - y1
Sign up to request clarification or add additional context in comments.

2 Comments

It is required in my assignment, that I am not supposed to change the function header, as we are supposed to use the tester provided to us
@Sal you can easily wrap this function to achieve the original signature, since you can convert Point a to Point b whenever Real a and Fractional b.
0
type Point a = (a,a)
distance :: (Real a, Floating b) => Point a -> Point a -> b
distance (x1,y1) (x2,y2) = sqrt ((dx * dx) + (dy * dy))
  where dx = realToFrac $ x2 - x1
        dy = realToFrac $ y2 - y1

2 Comments

This is now the correct solution, but IMO “here have the working code” answers are not great to homework questions.
its not the exact answer I m looking for, and this was just a small function from the a larger project

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.