Haskell rules for selecting type instances for Int, Double, and Integer

I would like to know which rules used by Haskell to always decide for an Integer instance instead of others when evaluating expressions in GHCi 1 .+. 2:

import Debug.Trace

class MyFuns a where
    (.+.) :: a โ†’  a โ†’  a

instance MyFuns Double where
    x .+. y = trace "Double " $ x + y

instance MyFuns Integer where
    x .+. y = trace "Integer " $ x + y

instance MyFuns Int where 
    x .+. y = trace "Int " $ x + y

EDIT : if I add the following code to the end of the file

main = do
   let x = 1 .+. 2
   print x

why am i getting this error?

No instance for (Num a0) arising from the literal โ€˜1โ€™
The type variable โ€˜a0โ€™ is ambiguous
Relevant bindings include x :: a0 (bound at fun2.hs:19:7)
Note: there are several potential instances:
  instance Integral a => Num (GHC.Real.Ratio a)
    -- Defined in โ€˜GHC.Realโ€™
  instance Num Integer -- Defined in โ€˜GHC.Numโ€™
  instance Num Double -- Defined in โ€˜GHC.Floatโ€™
  ...plus three others
In the first argument of โ€˜(.+.)โ€™, namely โ€˜1โ€™
In the expression: 1 .+. 2
In an equation for โ€˜xโ€™: x = 1 .+. 2

However, if I load the file at the GHCi prompt without main = ..., and then type 1 .+. 2, GHCi prints 3as expected. Why is this behavior?

thanks

+4
source share
1 answer

. 4.3.4 Haskell. Haskell , ( ), ( ) Num a => a. , , , Integer. , Fractional a => a, Double.

default , , :

default (Int, Float)

Num Int Fractional Float ( Int Fractional). , , .

( ):

, . , .

-XExtendedDefaultRules GHC , . .


Edit

, , GHC 4.3.4 :

, GHCi Haskell ( 4.3.4 Haskell 2010) . (C1 a, C2 a,..., Cn a) a if

  • a

  • Ci .

  • , Ci .

. .+., MyFuns - Prelude , "" . , :

GHCi GHC, -XExtendedDefaultRules, :

  • 2 : Ci .

  • 3 : , Ci Show, Eq Ord.

  • () , .

, ExtendedDefaultRules (, , GHCi ), :

{-# LANGUAGE ExtendedDefaultRules #-}

import Debug.Trace

default (Int, Float, Double)

class MyFuns a where
    (.+.) :: a -> a -> a

instance MyFuns Double where
    x .+. y = trace "Double " $ x + y

instance MyFuns Integer where
    x .+. y = trace "Integer " $ x + y

instance MyFuns Int where
    x .+. y = trace "Int " $ x + y

main = do
   print $ 1 .+. 2 -- Interpreted as Int

, 1.0 .+. 2.0 double, 1.0 + 2.0 float: , Float MyFuns, default .

+5

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


All Articles