Haskell で型システムがどのように機能するかを理解しようとしています。
class (Show a) => MyShow a where
myShow :: a -> String
instance MyShow Integer where
myShow = show
myshow :: (Show a) => a -> String
myshow = show
main = do
putStrLn $ myshow 1
putStrLn $ myShow (2 :: Integer) -- why do I need '::Integer' here?
「myshow 1」はタイプなしで機能するのに、「myShow 2」は明示的なタイプなしでエラーを引き起こすのはなぜですか:
Ambiguous type variable `a0' in the constraints:
(MyShow a0) arising from a use of `myShow'
at nooverinst.hs:12:16-21
(Num a0) arising from the literal `2' at nooverinst.hs:12:23
Probable fix: add a type signature that fixes these type variable(s)
In the second argument of `($)', namely `myShow 2'
In the expression: putStrLn $ myShow 2
In the expression:
do { putStrLn $ myshow 1;
putStrLn $ myShow 2 }
また奇妙なのは、GHCI を使用するとエラーが発生しないことです。
*Main> myShow 2
"2"
では、この場合の「myshow」と「myShow」の違いは何ですか? どちらも「show」と同じように定義されています。私は何が欠けていますか?
アップデート:
回答の要約: この動作は、デフォルト設定に関係しています。'show 1' と 'myshow 1' が機能するという事実は特殊なケースです (デフォルト設定に関する Haskell レポートのセクションを参照してください)。ソース コードの上に 'default ()' を追加すると、デフォルト設定がオフになり、'myshow 1' でコードが壊れます。したがって、実際には、両方の putStrLn 行の末尾に型シグネチャが必要です。
答えてくれたみんなありがとう!