Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it is impossible to divide Integer number in Haskell?

Tags:

haskell

This code

(4 :: Integer) / 2

will lead to error:

  No instance for (Fractional Integer) arising from a use of ‘/’
    In the expression: (4 :: Integer) / 2
    In an equation for ‘it’: it = (4 :: Integer) / 2

Why?

I need to specify

fromIntegral(4 :: Integer) / 2

to get a result. But what if I need a real number and not 2.0?

like image 568
barbara Avatar asked Mar 11 '16 21:03

barbara


People also ask

Can an integer be divided?

Division of integers involves the grouping of items. It includes both positive numbers and negative numbers. Just like multiplication, the division of integers also involves the same cases. When you divide integers with two positive signs, Positive ÷ Positive = Positive → 16 ÷ 8 = 2.

What happens when an int is divided by an int?

When dividing an integer by an integer, the answer will be an integer (not rounded).

What is the rule regarding integer division?

DIVISION. RULE 1: The quotient of a positive integer and a negative integer is negative. RULE 2: The quotient of two positive integers is positive. RULE 3: The quotient of two negative integers is positive.


1 Answers

Because the Integer type has no Fractional instance.

The type for (/) is Fractional a => a -> a -> a. Consider what happens when a = Integer. You'd have Integer -> Integer -> Integer. But 1/2 is not an integer, it's 0.5. So the only way to fit the division operator would be to round the result. But there is not a single way to round, and the best choice depends on the application, hence it was decided to not provide that instance.

If you want to perform integer division use the div or quot functions (they use different rounding). Otherwise convert to something that supports a well-defined division operation like Rational (this is what the fromIntegral is doing).

like image 172
Bakuriu Avatar answered Sep 20 '22 18:09

Bakuriu