0

Trying understand an error message I got from a line of Haskell I wrote. I changed

f x = map digitToInt $ show x

to

f = \x -> map digitToInt (show x)
  = (map digitToInt).(\x -> show x)
  = (map digitToInt).show

and got the following error message on compilation.

No instance for (Show a0) arising from a use of ‘show’
The type variable ‘a0’ is ambiguous
Relevant bindings include
  toDigits :: a0 -> [Int] (bound at lab2.hs:14:1)
Note: there are several potential instances:
  instance Show Data.Char.GeneralCategory -- Defined in ‘Data.Char’
  instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’
  instance Show Ordering -- Defined in ‘GHC.Show’
  ...plus 23 others
In the second argument of ‘(.)’, namely ‘show’
In the expression: (map digitToInt) . show
In an equation for ‘toDigits’: toDigits = (map digitToInt) . show

Wondering what the compiler is slapping me on the wrist for. show is of type Show a => a -> String (=[Char]) and (map digitToInt) :: [Char] -> [Int] so composition of these to morphisms should make sense.

Further, when I run it as a line (map digitToInt).show $ <some #> or ((map digitToInt).show) <some #> directly in the GHCi it works exactly as i want it to. So the function itself encodes the correct behavior.

Tshimanga
  • 845
  • 6
  • 16
  • There's nothing wrong with `f x = map digitToInt $ show x`. Are you typing that into `ghci` without a `let`? Have you imported `digitToInt` from `Data.Char`? What error did you get from `f x = map digitToInt $ show x`? – Cirdec Nov 01 '15 at 18:10
  • This is due to the monomorphism restriction. Your definition is not done through a function binding (but with a simple binding `f = ...`), so the MR applies. Try adding a type signature to work around that., e.g. `f :: Show a => a -> [Int]` before the function definition. – chi Nov 01 '15 at 18:14
  • Alternatively, disable the MR for the whole module adding at the top `{-# LANGUAGE NoMonomorphismRestriction #-}`. – chi Nov 01 '15 at 18:22
  • Indeed the problem. Thanks for the reference. Very happy with the thorough and well written answer there. Cheers! – Tshimanga Nov 01 '15 at 20:58

0 Answers0