Why am I forced to specify a type here?

I have the following code:

class ToString a where
    toString :: a -> String

instance ToString String where
    toString a = a

instance ToString Char where
    toString a = [a]

instance ToString Int where
    toString a = show a

instance ToString Integer where
    toString a = show a

instance ToString Float where
    toString a = show a

instance ToString Double where
    toString a = show a

I can do toString "Text"both toString 't', and both compile in order. But if I do toString 5, I will get an error. I have to do it toString (5::Int).

showno type specified for operation is needed. And when I look at implementations show, I don't see anything magical:

instance Show Int where ...

instance Show Integer where ...

What am I doing wrong, what requires me to specify the type and how to fix it?

UPDATE:

I added {-# LANGUAGE ExtendedDefaultRules #-}as suggested below and it worked perfectly. Solved my problem.

+4
source share
2 answers

You need to specify a type because it 5is polymorphic in Haskell:

λ> :type 5
5 :: Num a => a

, Num . - ghci:

λ> toString 5
"5"
+7

toString "Text" toString 't', Haskell , "Text" 't': [Char] (aka String) Char . , .

toString 5 . , 5, Haskell, 5 Int, a Double - Num, ToString. , ToString ( , Int Double). Haskell ​​ , , , -, .

Haskell , , , , , , Haskell. 1

, :

  • , (Num, Floating ..)

, show 5 , 5 (Num a, Show a); Num - , .

toString 5 , , (Num a, ToString a), ToString , , .

, GHCi ( ExtendedDefaultRules), " " ( ), (Num a, ToString a) .

GHC , GHCi ( ExtendedDefaultRule), :

https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/ghci.html#type-defaulting-in-ghci


1 , ( , ), , () . GHC , , , , .

, toString x , , x Int. , x , , Int. - , Int. Etc ..

GHCi , , , . ( ) , GHCi.

+5

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


All Articles