[Haskell-beginners] '/' instead use 'DIV'. why?

Ut Primum utprimum at gmail.com
Fri Apr 17 08:10:46 UTC 2020


Hi,
as you said, the operator (/) takes arguments that belong to the class
*Fractional* (instances of this class are the types *Double* and *Float*).

The function length has type:
Prelude> :t length
length :: Foldable t => t a -> Int
this means that it takes a list and returns something of type Int, In fact
Prelude> :t (length [23,34,45])
(length [23,34,45]) :: Int

Since Int is *not* an instance of the class Fractional, you can't use (/).
Instead Int is an instance of the class Integral, so you can use div with
arguments of type Int.

The example 6/3 works because you didn't assign any type to those numbers,
so they are seen as belonging to the class Num.
Prelude> x=6
Prelude> :t x
x :: Num p => p
This means that they can be seen both as Integral and Fractional and you
can use them with both functions that take Integral arguments and functions
that take Fractional arguments.

If you specify that for example 6 is an Int you can't use (/) any more:
Prelude> x::Int; x=6;
Prelude> x/3
<interactive>:20:1: error:
    • No instance for (Fractional Int) arising from a use of ‘/’
>From the error message you can see that the problem is as I said before
that Int is not an instace of the class Fractional.

Hope is clear
Best,
Ut

Il ven 17 apr 2020, 09:20 Alexander Chen <alexander at chenjia.nl> ha scritto:

> Hi,
>
>
> Prelude> :t (/)
> (/) :: *Fractional* a => a -> a -> a
>
> Prelude> :t div
> div :: *Integral* a => a -> a -> a
>
>
> Prelude> 6 / length [23,34,45]
> error
>
> Prelude> 6 / 3
> 2.0
>
> Could somebody explain to me why this is?
>
> thanks,
>
> Alexander Chen
>
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20200417/d9305e05/attachment.html>


More information about the Beginners mailing list