问题
I am following https://en.wikibooks.org/wiki/Haskell/Understanding_monads/State, and randomIO prints an integer in ghci directly. Given its type is polymorphic, how does ghci know it's Int here? Are there some special rules for type inference in ghci?
GHCi> :m System.Random
GHCi> :t randomIO
randomIO :: Random a => IO a
GHCi> randomIO
-1557093684
GHCi> randomIO
1342278538
回答1:
I suppose it is just simple Monomorphism restriction. Polymorphic types such as Num a => a are handled like Integer if actual type is not specified. Probably this rule also works in ghci and you see integer type instead of some unknown type variable.
UPD 1: actually the real answer contained under this part of user guide about defaulting rules.
UPD 2: Case with Random type class turned to be more difficult than I expected. So in this case defaulting rules are resolved due to default (Integer, Double) declaration which is said in report. Consider next ghci session
Prelude System.Random> default ()
Prelude System.Random> randomIO
<interactive>:6:1:
No instance for (Show (IO a0)) arising from a use of ‘print’
In a stmt of an interactive GHCi command: print it
Prelude System.Random> default (Integer)
Prelude System.Random> randomIO
-7948113563809442883
Prelude System.Random> default (Double)
Prelude System.Random> randomIO
0.41581766590151104
来源:https://stackoverflow.com/questions/39251728/ghci-randomio-type-inference