Why is "1/2" compiled when there is no (/) defined in Num?

Sorry for the newbies question, but I really don't understand the overloaded values:

GHCi, version 7.8.3: http://www.haskell.org/ghc/  :? for help
Prelude> let x = 1
Prelude> let y = 2

Both xand yhave a type Num a => a. But Numno (/)! So why does a type expression x / ycheck?

Prelude> x / y
0.5

(/)defined in class Fractional. Is there an implicit conversion from Numto Fractional?

UPD

So, as expected, I got answers in which people claim to x / y aspecialize in Fractional a => a.

I created my own hierarchy of numbers:

data MyInt = MyInt Integer deriving Show
data MyDouble = MyDouble Double deriving Show

class MyNum a where
    (+#) :: a -> a -> a -- + renamed to +# to avoid collision with standard +
    myFromInteger :: MyNum a => Integer -> a

class MyNum a => MyFractional a where
    (/#) :: a -> a -> a

instance MyNum MyInt where
    (MyInt a) +# (MyInt b) = MyInt (a + b)
    myFromInteger i = MyInt i

instance MyNum MyDouble where
    (MyDouble a) +# (MyDouble b) = MyDouble (a + b)
    myFromInteger i = MyDouble (fromInteger i)

instance MyFractional MyDouble where
    (MyDouble a) /# (MyDouble b) = MyDouble (a / b)

If everything in the attributes is true, then a similar code, where Numreplaced by MyNum, should also work. But ghci reports an error:

Prelude> :load myint.hs
*Main> let x = myFromInteger 1
*Main> let y = myFromInteger 2
*Main> x /# y

<interactive>:14:1:
    No instance for (MyFractional a0) arising from a use of `it'
    The type variable `a0' is ambiguous
    Note: there is a potential instance available:
      instance MyFractional MyDouble -- Defined at myint.hs:19:10
    In the first argument of `print', namely `it'
    In a stmt of an interactive GHCi command: print it
+4
3

, ghci, NoMonomorphismRestriction. x y Num a => a:

Prelude> :set -XNoMonomorphismRestriction
Prelude> let x = 1
Prelude> let y = 2
Prelude> :t x
x :: Num a => a

, , Fractional a => a x/y:

Prelude> :t x/y
x/y :: Fractional a => a

Num Fractional, Fractional Num , , x y Fractional a => a. , - :

($) = id :: (a -> b) -> (a -> b)

$ id :: c -> c, c = a -> b. , , (.. ), Fractional a => a Num a => a.

ghci , / , . , Double, default .


, . :

Num , Haskell - :

default (t1 , ... , tn)

n>=0, ti , Num ti. , , variable, v, , :

  • v C v, C - , , (.. Num Num)
  • Prelude (. 6.2--6.3, - . 6.1, , .)
+6

x y Num a => a, , . " , , , Num", " , Num". , x / y " ", Num Fractional, , Fractional Num, " , Fractional, Rational Double.

, 1 / 2, , , , () 1 :: Double 2 :: Double : 1 Haskell , .

0

Haskell transforms the numerator into Fractionaland the fractional section blank. If you need to split Int, try using the infix operator div:

Prelude> x div y
-1
source

Source: https://habr.com/ru/post/1570503/


All Articles