How to print an empty literal list in Frege

78 views Asked by At

I tried

println [ ] 

but got

unknown context: Show <3298 a>

Is that not supported by design or is my code wrong?

1

There are 1 answers

1
Ingo On BEST ANSWER

The point is that the expression

[]

does not give any information about the list element type. But this information is needed to get it printed!

This seems absurd at first sight, but remember that the type class system allows us to print a list of A's differently than a list of B's. For example, in Haskell, a list of characters is not printed like

['n', 'o', 't', ' ', 's', 'o']

I think that in Haskell there is some type defaulting going on (at least in GHCi?), so it can be printed anyway. You may add the "haskell" tag to this question and ask for an explanation why it works in Haskell.

The solution, of course, is to add the missing type information:

println ([] :: [()])     -- for example

--------------- EDIT ------------------------

I checked the following code with GHC 7.6.2:

foo n = if n == 0 then print [] else print Nothing
main = foo 42

and it does give error messages:

Could not deduce (Show a0) arising from a use of `print'
...
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
...
In the expression: print []

Could not deduce (Show a1) arising from a use of `print'
...
The type variable `a1' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
...
In the expression: print Nothing

The bottom line is that ghci allows things that are not valid in Haskell source code. In fact, you can type:

let bar n = if n == 0 then print [] else print Nothing

but if you try to load the very same code it gives you the error messages above.