Pregunta

I want to to a simple Integer division, and I get this in Hugs

Hugs> :load prog.hs
ERROR file:prog.hs:30 - Instance of Fractional Int required for definition of lastf

My simple program goes like this

lastf::Int->Int
lastf 1 = 0 
lastf n = if even n then (2*n+1) else (n/2)

What am I doing wrong ? How can I simply do a division ?

¿Fue útil?

Solución

If you want to do integer division, just use div:

lastf n = if even n then 2 * n + 1 else n `div` 2

The reason why is because Int does not implement the / operator, it is reserved for Fractional types, like Float and Double. Obviously, if you do 3 / 2 and you want 1.5 back, you can't represent that as an Int, you'd have to use a Float or Double (or any type that implements the Fractional typeclass).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top