2016-07-18 34 views
0

這是haskell代碼。我發現爲什麼我在下面錯了。在Haskell中打印空列表

main = do 
    print [1] -- Okay 
    print [] -- error 

錯誤字符串如下。

P07.hs:38:11: error: ? Ambiguous type variable ‘t0’ arising from a use of ‘print’ prevents the constraint ‘(Show t0)’ from being solved. Probable fix: use a type annotation to specify what ‘t0’ should be. These potential instances exist: instance Show Ordering -- Defined in ‘GHC.Show’ instance Show Integer -- Defined in ‘GHC.Show’ instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’ ...plus 22 others ...plus five instances involving out-of-scope types (use -fprint-potential-instances to see them all) ? In a stmt of a 'do' block: print [] In the expression: do { print [] } In an equation for ‘main’: main = do { print [] }

我試過[] :: Show無法正常工作。我想我只是不知道錯誤是什麼意思..請幫助我。 謝謝。

+0

請參閱[this](http://stackoverflow.com/a/23611674/382982)回答。 – pdoherty926

回答

3

Haskell中的列表在它們的元素類型中是多態的,並且由於[]包含的信息不足,您必須通過明確給出類型註釋[] :: [Int]來提供ghc。

您得到的錯誤是由於列表的Show實例取決於其元素的Show實例,並且由於ghc無法確定它假定ist沒有這樣的實例。現在

你可能會認爲一切都可以轉化爲String,但你能想到的Int -> Int並嘗試

​​

這將無法正常工作,在Haskell功能沒有默認Show實例。

+0

謝謝。它適用於'main = do([] :: [Int])' –

+0

我認爲它不應該這樣工作,我認爲你錯過了一個'print' – epsilonhalbe

+0

是的,我失敗了。 'main =打印([] :: [Int])'是正確的。再次感謝。 –