Last hour in school we started to learn Haskell. We use the Helium compiler because its fast and easy to use.
I started to type in standard functions like *
, +
... But the division does not work. I tried 5 / 2
or 4 / 2
and got this message:
"Type error in infix application
expression : 3 / 5
operator : /
type : Float -> Float -> Float
does not match : Int -> Int -> a "
How I can use the devision operator to get 2.5
from 5 / 2
?
I tried div 5 2
but then I got 2
and not 2.5
As per the documentation
- Numeric literals are not overloaded (even when using the
--overloading
flag). Thus,3
is of typeInt
and3.0
of typeFloat
. A consequence is that you can never write2 + 2.3
, although in overloaded mode you may write both2 + 3
and2.0 + 3.0
.
Additionally:
- There are five built-in type classes with the following instances:
- Num:
Int
,Float
So in order to get floating point division you will have to use explicit floating point literals, such as 5.0 / 2.0
.
It is worth noting that in Haskell itself (Helium is only a subset of Haskell) the expression 5 / 2
is well typed and would have the type Fractional a => a
, but Helium does not appear to have the Fractional
typeclass at all, only Int
and Float
as numeric types, so what is actually valid Haskell that would work as you would expect does not work in Helium.
If you are using Helium it appears that you would have probably installed it using cabal
as per the website's instructions:
> cabal install helium lvmrun
then you should have access to GHC and GHCi. Try running GHCi as your interactive shell to see if that helps. You may run into errors that are harder to read at first than Helium's, but Haskell's type errors are very informative in the vast majority of cases.
The error message says that /
expects floating-point ("real") numbers, and you provide integer numbers.
You can make the arguments explicitly floating-point: 5.0 / 2.0
.
You can convert values to floating point (works in GHC, didn't try Helium):
let a = 1::Int
let b = 2::Int
-- here a / b gives a type error like you reported
show $ fromIntegral a / fromIntegral b -- works
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.