[Haskell-beginners] '/' instead use 'DIV'. why?
utprimum at gmail.com
Fri Apr 17 08:10:46 UTC 2020
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> :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;
• 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
Il ven 17 apr 2020, 09:20 Alexander Chen <alexander at chenjia.nl> ha scritto:
> Prelude> :t (/)
> (/) :: *Fractional* a => a -> a -> a
> Prelude> :t div
> div :: *Integral* a => a -> a -> a
> Prelude> 6 / length [23,34,45]
> Prelude> 6 / 3
> Could somebody explain to me why this is?
> Alexander Chen
> Beginners mailing list
> Beginners at haskell.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Beginners