What is wrong with this code?
<code>
data Term = Constant Int | Divide Term Term
evaluate :: Term -> Int
evaluate (Constant a) = a
evaluate (Divide x y) = evaluate x / evaluate y
</code>
it gives this error
<error>
No Instance for (Fractional Int)
arising from a use of `/'
at (etc..)
In the expression evaluate x / evaluate y
In the definition of `evaluate':
evaluate (Divide x y) = evaluate x / evaluate y
</error>
Greetings from Nils
--
Nils-Hero Lindemann <ni...@freiewelt.org>
> evaluate :: Term -> Int
> evaluate (Constant a) = a
> evaluate (Divide x y) = evaluate x / evaluate y
>
> No Instance for (Fractional Int)
> arising from a use of `/'
Yup. You're dividing, but the function is declared to return an Int,
which can't be fractional, but division can give fractional results.
Perhaps you wanted to use `div` instead?
Mark
So all this works:
a) use div instead of (/)
--- snip ---
data Term = Constant Int | Divide Term Term
evaluate :: Term -> Int
evaluate (Constant a) = a
evaluate (Divide x y) = evaluate x `div` evaluate y
--- snip ---
b) Change the Constant's type into Float
--- snip ---
data Term = Constant Float | Divide Term Term
evaluate :: Term -> Float
evaluate (Constant a) = a
evaluate (Divide x y) = evaluate x / evaluate y
--- snip ---
c) convert Int to Float
--- snip ---
data Term = Constant Int | Divide Term Term
evaluate :: Term -> Float
evaluate (Constant a) = fromIntegral a
evaluate (Divide x y) = evaluate x / evaluate y
--- snip ---
Thank you for the hint, Marc
am Tue, 28 Dec 2010 18:14:29 -0500
schrieb "Mark T. B. Carroll" <mt...@bcs.org>:
> Yup. You're dividing, but the function is declared to return an Int,
> which can't be fractional, but division can give fractional results.
> Perhaps you wanted to use `div` instead?
>
> Mark
--
Nils-Hero Lindemann <ni...@freiewelt.org>
> What is wrong with this code?
>
> <code>
>
> data Term = Constant Int | Divide Term Term
>
> evaluate :: Term -> Int
> evaluate (Constant a) = a
> evaluate (Divide x y) = evaluate x / evaluate y
The problem is that / only works on values of types in the Fractional
typeclass. In general dividing an integer by an integer does not result
in an integer so we can see the above code is not well-typed, even on an
informal understanding of "well-typed".
--
Aatu Koskensilta (aatu.kos...@uta.fi)
"Wovon man nicht sprechen kann, darüber muss man schweigen"
- Ludwig Wittgenstein, Tractatus Logico-Philosophicus
> "Wovon man nicht sprechen kann, darüber muss man schweigen"
> - Ludwig Wittgenstein, Tractatus Logico-Philosophicus
Ludwig konnte eben nicht singen :-)
Danke auch an Dich
--
Nils-Hero Lindemann <ni...@freiewelt.org>