为什么GHC不能推断出这种类型呢?

时间:2016-08-27 06:27:41

标签: haskell ghc

请考虑以下代码段(来自http://lpaste.net/180651):

{-# LANGUAGE ScopedTypeVariables #-}

class Natural n

newtype V n a = V [a]

dim :: Natural n => V n a -> Int
dim = undefined -- defined in my actual code

bad_fromList :: Natural n => [a] -> V n a
bad_fromList l = if length l == dim v then v else undefined -- this is line 11
  where v = V l

good_fromList :: forall n a. Natural n => [a] -> V n a
good_fromList l = if length l == dim v then v else undefined
  where v = V l :: V n a

GHCI提供以下错误消息:

test.hs:11:33: error:
    • Could not deduce (Natural n0) arising from a use of ‘dim’
      from the context: Natural n
        bound by the type signature for:
                   bad_fromList :: Natural n => [a] -> V n a
        at test.hs:10:1-41
      The type variable ‘n0’ is ambiguous
    • In the second argument of ‘(==)’, namely ‘dim v’
      In the expression: length l == dim v
      In the expression: if length l == dim v then v else undefined

为什么GHCI不能推断这种类型?

或者,在下面的代码中,纯粹的'和good_f编译,而bad_f给出类似的错误消息。为什么呢?

pure' :: Natural n => a -> V n a
pure' x = v
  where v = V $ replicate (dim v) x

bad_f :: Natural n => [a] -> (V n a, Int)
bad_f xs = (v, dim v)
  where v = V xs

good_f :: Natural n => a -> (V n a, Int)
good_f x = (v, dim v)
  where v = V $ replicate (dim v) x

1 个答案:

答案 0 :(得分:0)

正如user2407038建议的那样,启用-XMonoLocalBinds可以使代码正常工作。