[Haskell-beginners] Question on fromIntegral

David McBride toad3k at gmail.com
Thu Dec 1 04:05:21 UTC 2022


It is because (**) takes floating point numbers. In your first equation
both 4s are different. The second 4 is an Integer but the first is a some
Floating type aka 4.0.

In your second equation, both of those numbers are constrained to whatever
type i is, and fact demands an Integer and (**) demands a Float or Double
or some other Floating type, which cannot be reconciled.

You should be able to fix this with (untested)  x**fromIntegral(i), which
converts i from an Integer to Num and all Floating are Nums.

On Wed, Nov 30, 2022, 19:41 Jonathan Drews <jondrews at fastmail.com> wrote:

> Hi Folks:
>
>  I am using Glasgow Haskell Compilation System, version 9.2.4 on
> OpenBSD 7.2. I am stumped by the following problem. If I run the
> following program in ghci, then it works fine. Look:
>
> fact :: Integer -> Integer
> fact n = product [1..n]
>
>
> term :: Double -> Double
> term x  = x**4/fromIntegral(fact(4))
>
> $ ghci
> GHCi, version 9.2.4: https://www.haskell.org/ghc/  :? for help
> ghci> :l seriesTermTest.hs
> [1 of 1] Compiling Main             ( seriesTermTest.hs, interpreted )
> Ok, one module loaded.
> ghci> term 1.0
> 4.1666666666666664e-2
>
> However if I use fromIntegral inside a list comprehension like so:
>
> fact :: Integer -> Integer
> fact n = product [1..n]
>
>
> expon :: Double -> Double
> expon x  = sum [x**i/fromIntegral(fact(i)) | i <- [0..50]]
>
> then I get the following error message:
>
> $ ghci
> GHCi, version 9.2.4: https://www.haskell.org/ghc/  :? for help
> ghci> :l ePowerSeries.hs
> [1 of 1] Compiling Main             ( ePowerSeries.hs, interpreted )
>
> ePowerSeries.hs:6:40: error:
>     * Couldn't match expected type `Integer' with actual type `Double'
>     * In the first argument of `fact', namely `(i)'
>       In the first argument of `fromIntegral', namely `(fact (i))'
>       In the second argument of `(/)', namely `fromIntegral (fact
> (i))'
>   |
> 6 | expon x  = sum [x**i/fromIntegral(fact(i)) | i <- [0..50]]
>   |                                        ^
> Failed, no modules loaded.
>
> What am I doing wrong?
>
> --
> Kind regards,
> Jonathan
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20221130/bf05e787/attachment.html>


More information about the Beginners mailing list