Haskell split error

In the last hour at school, we started studying Haskell. We use the helium compiler because its fast and easy to use.

I started to introduce standard functions like * , + ... But division does not work. I tried 5/2 or 4 / 2 and received this message:

 "Type error in infix application expression : 3 / 5 operator : / type : Float -> Float -> Float does not match : Int -> Int -> a " 

How can I use the devision operator to get 2.5 out of 5/2?

I tried div 5 2 but then got 2 , not 2.5

+5
source share
2 answers

In accordance with the documentation

  • Numeric literals are not overloaded (even when using the --overloading flag). So 3 is of type Int and 3.0 type Float . The consequence of this is that you can never write 2 + 2.3 , although in overloaded mode you can write both 2 + 3 and 2.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 have to use explicit floating point literals like 5.0 / 2.0 .


It is worth noting that in Haskell itself (helium is only a subset of Haskell), the 5/2 expression is well-typed and will have the type Fractional a => a , but helium does not seem to have the Fractional typeclass at all, only Int and Float as numeric types , so a really valid Haskell, which would work as you expected, does not work in Helium.

If you are using Helium, it looks like you probably installed it using cabal according to the instructions on the website:

 > cabal install helium lvmrun 

then you should have access to GHC and GHCi. Try running GHCi as an interactive shell to see if this helps. You may encounter errors that are harder to read at first than helium, but errors like Haskell are very informative in the vast majority of cases.

+9
source

The error message says / expects floating point numbers ("real"), and you provide integer numbers.

You can make the arguments explicitly float: 5.0 / 2.0 .

You can convert the values ​​to a floating point (works in GHC, did not 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 
+2
source

All Articles