haskell - Int vs Integer in class instance -


class visible  tostring :: -> string  size   :: -> int  inttostring :: (integral t) => t -> string inttostring 0 = "0" inttostring 1 = "1" inttostring 2 = "2" inttostring 3 = "3" inttostring 4 = "4" inttostring 5 = "5" inttostring 6 = "6" inttostring 7 = "7" inttostring 8 = "8" inttostring 9 = "9" inttostring n   | ((div n 10) == 0) = (inttostring (mod n 10))  | otherwise         = (inttostring (div n 10)) ++ (inttostring (mod n 10)) 

now

instance visible int  tostring = inttostring  size n   = length (tostring n) 

gives me error ambiguous type variable @ prompt if type (tostring 55)

but

instance visible integer  tostring = inttostring  size n   = length (tostring n) 

does not.

what gives?

there 2 things going on here. remember numeric literals in haskell polymorphic. is:

x = 55 

really means

x :: num => x = fromintegral 55 

this true numbers anywhere write them. can awkward work with, ghci implements type defaulting: assumes bare numbers integers or doubles if type ambiguous.

when write tostring 55 @ ghci prompt, ghci infers type (visible a, num a) => a number 55. if have visible int in scope, type default of integer doesn't work because doesn't fulfill class constraint (there's no visible integer), ghci complains ambiguous type variable because doesn't know type instantiate expression. if have visible integer in scope, type default of integer works fine.

if want use type other integer, can use explicit type in tostring (55 :: int)


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -