Can someone explain to me why 6 / 3
works but 6 / length [1, 2, 3]
errors out?
Here's the error in REPL
<interactive>:20:1: error:
• No instance for (Fractional Int) arising from a use of ‘/’
• In the expression: 6 / length [1, 2, 3]
In an equation for ‘it’: it = 6 / length [1, 2, 3]
(/)
has the type Fractional a => a -> a -> a
, so each of its arguments has to be a value of some type with a Fractional
instance.
Both 6
and 3
are polymorphic literals, having type Num a => a
. Thus, 6/3
has the type Fractional a => a
, since Fractional
is a subclass of Num
.
length
, however, always returns an Int
, and Int
does not have a Fractional
instance. The simplest fix is to use genericLength :: Num i => [a] -> i
from Data.List
instead, which can return a value of type Fractional a => a
that is suitable for second argument to (/)
:
>>> import Data.List
>>> 6 / genericLength [1,2,3]
2.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With