[Haskell-beginners] Haskell typing question
Henk-Jan van Tuyl
hjgtuyl at chello.nl
Tue Oct 28 13:38:51 UTC 2014
In the expression
\x acc -> acc / 10.0 + x
10.0 is a Fractional number, / is an operator that works on types in the
class Fractional, x is an Int, because the expression is applied to an Int.
To get the types correct, use fromIntegral:
caluDecimal l = (foldr1 (\x acc -> acc / 10.0 + x) (map (fromIntegral .
digitToInt) l))
(note, that you can write 10 instead of 10.0, with the same result.)
Regards,
Henk-Jan van Tuyl
On Tue, 28 Oct 2014 13:08:34 +0100, Cui Liqiang <cui.liqiang at gmail.com>
wrote:
> I got it!
>
> The msg “ No instance for (Fractional Int) arising from a use of `/‘ “
> actually has no business with the operands order at all !
>
> --
> Cui Liqiang
>
>
> On Tuesday, October 28, 2014 at 8:00 PM, Cui Liqiang wrote:
>
>> Thanks for your help, your suggestion works.
>>
>> But I still don’t quite understand. In the following line:
>> caluDecimal l = (foldr1 (\x acc -> acc / 10.0 + x) (map digitToInt l)),
>> After applying digitToInt, the type of ‘x’ in the expression above is
>> Int indeed, but Haskell consider the ’10.0’ to be a Int, is it?
>>
>>
>>
>>
>> ----------------------------------------------------------------------------------------------------------------------------
>> Hi,
>> I am doing an exercise in Haskell, which is converting a string like
>> ?$123.312? to double value. Below is my code:
>>
>> module Main where
>> import Data.Char
>>
>> caluInt l = foldl1 (\acc x -> acc * 10 + x) (map digitToInt l)
>> caluDecimal l = (foldr1 (\x acc -> acc / 10.0 + x) (map digitToInt l))
>>
>> convert(x:xs) =
>> let num = [e | e <- xs, e /= ',']
>> intPart = takeWhile (/='.') num
>> decimalPart = tail(dropWhile (/='.') num)
>> in (caluInt intPart) + (caluDecimal decimalPart)
>>
>>
>> And I got an error in this line: caluDecimal l = (foldr1 (\x acc -> acc
>> / 10.0 + x) (map digitToInt l)),
>> which says:
>> No instance for (Fractional Int) arising from a use of `/'
>> Possible fix: add an instance declaration for (Fractional Int)
>> In the first argument of `(+)', namely `acc / 10.0'
>> In the expression: acc / 10.0 + x
>> In the first argument of `foldr1', namely
>> `(\ x acc -> acc / 10.0 + x)'
>>
>>
>> Why Haskell insists that 10.0 is a Int? How can I explicitly tell
>> Haskell I want a Fractional?
:
>> Because digitToInt means exactly what it says. If you want it to become
>> something other than Int, apply fromIntegral to its result.
>>
>>
>
>
--
Folding at home
What if you could share your unused computer power to help find a cure? In
just 5 minutes you can join the world's biggest networked computer and get
us closer sooner. Watch the video.
http://folding.stanford.edu/
http://Van.Tuyl.eu/
http://members.chello.nl/hjgtuyl/tourdemonad.html
Haskell programming
--
More information about the Beginners
mailing list