types - Haskell: No instance arising -
beginning haskell, encounter problems types (and less helpful error messages of ghc). defined following function:
ghci> let f x = floor x == x ghci> :t f f :: (integral a, realfrac a) => -> bool
which succeeds, invocation seams difficult:
ghci> let = 1.1 ghci> f <interactive>:296:1: no instance (integral double) arising use of `f' possible fix: add instance declaration (integral double) in expression: f in equation `it': = f ghci> let b = 2 ghci> f b <interactive>:298:1: no instance (realfrac integer) arising use of `f' possible fix: add instance declaration (realfrac integer) in expression: f b in equation `it': = f b
how define function correctly?
haskell doesn't any automatic coercion between different numeric types if e.g. compare x == y
x
, y
have have exact same type (e.g. both ints or both floats).
now, if @ type of floor
it's
floor :: (integral b, realfrac a) => -> b
which means can call fractional types , result type must integral type.
when call f 1.1
inside f
end making comparison
floor 1.1 == 1.1
but have problem because floor
can return integral types , in order make comparison result has have same type 1.1
not integral.
you need define f
as
let f x = fromintegral (floor x) == x
the fromintegral
call coerces integral floor value fractional value can compared original x
.
Comments
Post a Comment