1
votes

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
2
have you tried applying realToFrac to the result of sqrt?jakubdaniel

2 Answers

2
votes

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
0
votes
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