[英]How to print an empty literal list in Frege
我试过了
println [ ]
但是得到了
unknown context: Show <3298 a>
是设计不支持的,还是我的代码错误?
关键是表达
[]
不提供有关列表元素类型的任何信息。 但是,需要此信息才能将其打印出来!
乍一看,这似乎很荒谬,但请记住,类型类系统使我们可以打印出与B列表不同的A列表。 例如,在Haskell中,字符列表不会像
['n', 'o', 't', ' ', 's', 'o']
我认为在Haskell中有某种类型的默认设置(至少在GHCi中是这样),因此无论如何都可以打印出来。 您可以在此问题上添加“ haskell”标签,并要求解释为什么它在Haskell中有效。
解决方案当然是添加缺少的类型信息:
println ([] :: [()]) -- for example
---------------编辑------------------------
我使用GHC 7.6.2检查了以下代码:
foo n = if n == 0 then print [] else print Nothing
main = foo 42
并且确实给出错误消息:
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
底线是,ghci中允许的事情是不是在Haskell源代码有效。 实际上,您可以输入:
let bar n = if n == 0 then print [] else print Nothing
但是如果您尝试加载完全相同的代码,则会收到上述错误消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.