引き続きReal World HaskellのP.245 10.4 暗黙の状態
試しに以下のような関数を書いてみた
f x y z = x * y * z
これをghciで:loadすると
*Main> :load testset.hs [1 of 1] Compiling Main ( testset.hs, interpreted ) Ok, modules loaded: Main. *Main> f 1 2 3 6 *Main> :t f f :: (Num a) => a -> a -> a -> a *Main> f 2.1 3.4 4.5 32.129999999999995
となる。
自然数でも小数でも適用できる。
今度は、ソース上で型を指定してみる。
f :: Int -> Int -> Int -> Int f x y z = x * y * z
*Main> :load testset.hs [1 of 1] Compiling Main ( testset.hs, interpreted ) Ok, modules loaded: Main. *Main> :t f f :: Int -> Int -> Int -> Int *Main> f 1 2 3 6 *Main> f 1.1 3.4 5.6 <interactive>:1:10: No instance for (Fractional Int) arising from the literal `5.6' at <interactive>:1:10-12 Possible fix: add an instance declaration for (Fractional Int) In the third argument of `f', namely `5.6' In the expression: f 1.1 3.4 5.6 In the definition of `it': it = f 1.1 3.4 5.6
自然数は適用できるけど、小数だとダメ。
これは、型を書かないとghciが型推論してくれて、ソースに書くと
そこで指定された型になるからだと思う。
では、さらにソースでマッチしない型を書いてみる。
f :: Int -> Int -> Int -> Int -> Int f x y z = x * y * z *Main> :load testset.hs [1 of 1] Compiling Main ( testset.hs, interpreted ) testset.hs:2:10: Couldn't match expected type `Int -> Int' against inferred type `Int' In the expression: x * y * z In the definition of `f': f x y z = x * y * z Failed, modules loaded: none.
当然エラーになるわな。
じゃぁなんで、Real World HaskellのP.245 10.4 暗黙の状態の
Parse.hsだとOKなんだろ?
これだと
ソースに書いた
runParse :: ParseState -> Either String (a, ParseState)
が
runParse :: Parse a -> ParseState -> Either String (a, ParseState)
に書き換わってるんだけど。
ParseStateがParse a -> ParseStateに変わってしまうのは何故?
parse関数の型は、
parse :: Parse a -> L.ByteString -> Either String a
と明記されていて、runParseの型も
ParseState -> Either String (a, ParseState)
と明記されているので、充分コンパイルエラーになると思うのだけど。