2016-07-18 6 views
0

これは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

ハスケルのリストは、その要素の型が多態的です。例えば、[]には、型の注釈を明示的に与えることによって、ghcに十分な情報を与えなければなりません。[] :: [Int]

リストのShowインスタンスが要素のShowインスタンスに依存し、ghcがistにそのようなインスタンスが存在しないと判断できないことが原因でエラーが発生しています。

今、あなたはすべてがStringに変換することができると思うかもしれませんが、あなたはInt -> Int考えるとHaskellの関数にはデフォルトShowインスタンスを持っていないと動作しません

​​

を試みることができます。

+0

ありがとうございます。それは 'main = do([] :: [Int])'で動作します。 –

+0

私はそれがうまくいかないと思う、あなたは 'print'を見逃していると思う。 – epsilonhalbe

+0

はい、失敗しました。 'main = do print([] :: [Int])'が正しいです。再度、感謝します。 –