14

このプログラムを GHC でコンパイルする場合:

import Control.Monad

f x = let
  g y = let
    h z = liftM not x
    in h 0
  in g 0

エラーが表示されます:

test.hs:5:21:
    Could not deduce (m ~ m1)
    from the context (Monad m)
      bound by the inferred type of f :: Monad m => m Bool -> m Bool
      at test.hs:(3,1)-(7,8)
    or from (m Bool ~ m1 Bool, Monad m1)
      bound by the inferred type of
               h :: (m Bool ~ m1 Bool, Monad m1) => t1 -> m1 Bool
      at test.hs:5:5-21
      `m' is a rigid type variable bound by
          the inferred type of f :: Monad m => m Bool -> m Bool
          at test.hs:3:1
      `m1' is a rigid type variable bound by
           the inferred type of
           h :: (m Bool ~ m1 Bool, Monad m1) => t1 -> m1 Bool
           at test.hs:5:5
    Expected type: m1 Bool
      Actual type: m Bool
    In the second argument of `liftM', namely `x'
    In the expression: liftM not x
    In an equation for `h': h z = liftM not x

なんで?fまた、 ( )に明示的な型シグネチャを指定f :: Monad m => m Bool -> m Boolすると、エラーが消えます。fしかし、これは、エラー メッセージによると、Haskell が自動的に推測する型とまったく同じ型です!

4

1 に答える 1

5

実際、これは非常に簡単です。バインドされた変数の推論された型はlet、型スキームに暗黙的に一般化されるため、途中で数量詞があります。の一般化されたタイプhは次のとおりです。

h :: forall a m. (Monad m) => a -> m Bool

の一般化されたタイプfは次のとおりです。

f :: forall m. (Monad m) => m Bool -> m Bool

それらは同じではありませんm。次のように記述した場合、本質的に同じエラーが発生します。

f :: (Monad m) => m Bool -> m Bool
f x = let
  g y = let
    h :: (Monad m) => a -> m Bool
    h z = liftM not x
    in h 0
  in g 0

そして、「スコープ型変数」拡張機能を有効にすることで修正できます。

{-# LANGUAGE ScopedTypeVariables #-}

f :: forall m. (Monad m) => m Bool -> m Bool
f x = let
  g y = let
    h :: a -> m Bool
    h z = liftM not x
    in h 0
  in g 0

letまたは、「モノモーフィック ローカル バインディング」拡張機能を使用して -generalisation を無効にすることにより、 MonoLocalBinds.

于 2013-07-20T20:07:09.677 に答える