Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't 6 / length [1, 2, 3] work in Haskell

Tags:

types

haskell

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]
like image 696
Croisade Avatar asked Feb 08 '21 17:02

Croisade


1 Answers

(/) 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
like image 68
chepner Avatar answered Nov 02 '22 11:11

chepner