Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Lack of) Ambiguous Type When Using Read and Show in Haskell

I wrote a very simple Haskell program:

main = print $ sum $ map read ["55", "99", "101"]

Given my past experience, I expected to get an "ambiguous type" error, since the signature of sum $ map read [...] is (Read a, Num a) => a; Num is a class and thus cannot itself implement the Show class. However, the program correctly outputted "255". How was print able to determine the method of producing the output? (show also is able to produce the correct result with no error.)

like image 789
Tanaki Avatar asked Mar 18 '23 02:03

Tanaki


1 Answers

If you use the -fwarn-type-defaults option you'll get this:

$ ghc -O2 -fwarn-type-defaults ddd.hs
[1 of 1] Compiling Main             ( ddd.hs, ddd.o )

ddd.hs:2:8: Warning:
    Defaulting the following constraint(s) to type ‘Integer’
      (Show s0) arising from a use of ‘print’ at ddd.hs:2:8-12
      (Read s0) arising from a use of ‘read’ at ddd.hs:2:26-29
      (Num s0) arising from a use of ‘sum’ at ddd.hs:2:16-18
    In the expression: print
    In the expression: print $ sum $ map read ["55", "99", "101"]
    In an equation for ‘main’:
        main = print $ sum $ map read ["55", "99", "101"]

which explains what is going on.

like image 82
ErikR Avatar answered Mar 26 '23 10:03

ErikR