haskell - No instance for (Show a0) arising from a use of `print' The type variable `a0' is ambiguous -


data nestedlist = elem | list [nestedlist a] flatten :: nestedlist -> [a] flatten (elem element) = [element] flatten (list []) = [] flatten (list (first:rest)) = flatten first ++ flatten (list (rest)) main = print $ flatten $ list [] 

i wrote above seen code in haskell. when execute other parameter, example

main = print $ flatten $ list [elem 1, elem 2] main = print $ flatten $ elem 1 

it gives

[1, 2] [1] 

respectively.

it fails when execute empty list.

main = print $ flatten $ list [] 

error message

no instance (show a0) arising use of `print' type variable `a0' ambiguous possible fix: add type signature fixes these type variable(s) note: there several potential instances:   instance show double -- defined in `ghc.float'   instance show float -- defined in `ghc.float'   instance (integral a, show a) => show (ghc.real.ratio a)     -- defined in `ghc.real'   ...plus 23 others in expression: print in expression: print $ flatten $ list [] in equation `main': main = print $ flatten $ list [] 

questions

  1. why fail , how can fix this?
  2. should change nestedlist definition accept empty list? if so, how do that. quite confusing.

the problem compiler can't know type of flatten $ list []. try figure out type yourself, you'll see it's [a] a, whilst print requires argument instance of show, , [a] instance of show if a instance of show. though list empty, there's no need constraint on a represent [], there's no way compiler know.

as such, putting explicit type annotation (for type instance of show exists) should work:

main = print $ flatten $ list ([] :: [nestedlist int]) 

or

main = print $ flatten $ list ([] :: [nestedlist ()]) 

or

main = print fl       fl :: [()]     fl = flatten $ list [] 

Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -