3
votes

I have run into a problem when trying to add 2 parts of a tuple together

Function Type:

close :: (Floating a, Ord a) => (a,a) -> (a,a) -> Float

Function definition:

close y x = sqrt (((fromIntegral(snd x) - fromIntegral(snd y))^2) + ((fromIntegral(fst x) - fromIntegral(fst y)^2)))

On feeding the function a y tuple of format ( , ) and a x tuple of format ( , ) it should calculate the distance between two coordinates. However on launch I get an error of:

Couldn't match expected type 'Float' with actual type 'a'
a is a rigid type variable bound by...

I do understand why the problem is arising, but I have no idea how to fix it

2
You mention Floating a in type definition and then feed fromIntegral in the function with the same a type which is supposed to belong Integral type class... which is a conflict.Redu
You need a function Floating a => a -> Float to produce the result. I would expect close :: Floating a => (a,a) -> (a,a) -> a, or close :: (Integral a, Floating b) => (a,a) -> (a,a) -> b. Where do Ord and Float come from?molbdnilo
@molbdnilo maybe he wants a concrete Float from the output?Adam Smith
@molbdnilo yes, I have no idea why i had float.... I think I just didnt realise that I can use a as the ambiguous for floatSoMax

2 Answers

2
votes

Your type is wrong. As Redu mentions in the comments, you have a type under typeclass Floating and are calling fromIntegral on it.

Prelude> :t fromIntegral
fromIntegral :: (Num b, Integral a) => a -> b

You can't have a Floating Integral, so this fails. Your type instead should be:

close :: Integral a => (a, a) -> (a, a) -> Float

Note that you also don't need as many fromIntegral calls, since (^) operates on (Num a, Integral b) => a -> b -> a, any number can be the base. The only operation that matters is sqrt which requires a Floating a.

close :: Integral a => (a, a) -> (a, a) -> Float
close (x1, y1) (x2, y2) = sqrt . fromIntegral $ squaredDistance where
  squaredDistance = (x1 - x2) ^ 2 + (y1 - y2) ^ 2
0
votes

One technique to help you debug this would be to comment out your type signature and ask the system what the type is. In ghci, that'll be :t close.