[英]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.