Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division error in Haskell

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

like image 550
noxus Nexus Avatar asked May 06 '15 15:05

noxus Nexus


1 Answers

As per the documentation

  • Numeric literals are not overloaded (even when using the --overloading flag). Thus, 3 is of type Int and 3.0 of type Float. A consequence is that you can never write 2 + 2.3, although in overloaded mode you may 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 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.

like image 107
bheklilr Avatar answered Oct 08 '22 15:10

bheklilr