Type signature of a function to find the magnitude of a vector
The following type signature to find the magnitude of a vector represented as a tuple doesn't seem to work:
mag :: (Floating b, Num a) => (a,a) -> b
mag (x,y) = sqrt (x**2 + y**2)
The error:
Couldn't match expected type `b' against inferred type `a'
`b' is a rigid type variable bound by
the type signature for `mag' at tone.hs:1:17
`a' is a rigid type variable bound by
the type signature for `mag' at tone.hs:1:24
In the expression: sqrt (x **开发者_如何学C 2 + y ** 2)
In the definition of `mag': mag (x, y) = sqrt (x ** 2 + y ** 2)
One way to compute a type signature is to ask the compiler to do the type inference for you:
Prelude> let mag (x,y) = sqrt (x**2 + y**2)
Prelude> :t mag
mag :: Floating a => (a, a) -> a
This is probably the type you want.
Now, your type takes a pair of a's and somehow converts them to a b in the Num
class. Do you mean to have a conversion to the more general Num
class there? If so, you'll need truncate
or some thing like it, and a fromIntegral
.
My guess is that this isn't what you want, but you can do it,
Prelude> let mag (x,y) = fromIntegral . truncate $ sqrt (x**2 + y**2)
Prelude> :t mag
mag :: (Floating a, RealFrac a, Floating a) => (a, a) -> c
精彩评论