2

下面的to_c函数由于类型错误而被拒绝,因为在使用我想用于此处未显示的不相关代码片段的 GADTs 扩展进行编译时。

newtype Church = Church { unC :: forall a. (a -> a) -> a -> a }
to_c :: Int -> Church
to_c 0 = let f0 f c = c in Church f0
to_c n =
    let fn f c = iterate f c !! n in Church fn

错误信息:

Couldn't match type ‘a0’ with ‘a’ because type variable ‘a’ would escape its scope
  This (rigid, skolem) type variable is bound by
    a type expected by the context:
      (a -> a) -> a -> a

  Expected type: (a -> a) -> a -> a
    Actual type: (a0 -> a0) -> a0 -> a0
  In the first argument of ‘Church’, namely ‘fn’

我可以以直接递归的方式重写函数,该函数将进行类型检查并且也可以工作;但是,我很好奇为什么这种迭代方法有缺陷,以及是否可以通过一些巧妙的类型注释来挽救它。

4

1 回答 1

6

这实际上与 GADT 没有任何关系,只是,-XGADTs扩展名也意味着-XMonoLocalBinds,这才是真正的问题。它的作用是,因为本地绑定fn没有明确的签名,它想给它一个不比环境多态的类型......即在这种情况下根本不是多态的。但是当然,它必须是多态的,所以它实际上可以在Church类型中使用,所以这不好。

您仍然可以给出明确的多态签名:

{-# LANGUAGE RankNTypes, MonoLocalBinds #-}
newtype Church = Church { unC :: forall a. (a -> a) -> a -> a }
to_c :: Int -> Church
-- to_c 0 = ...  -- the base case is redundant.
to_c n =
    let fn :: (a -> a) -> a -> a
        fn f c = iterate f c !! n
    in Church fn

但更简单的解决方案是根本不进行任何绑定,然后-XMonoLocalBinds就不会发挥作用:

to_c :: Int -> Church
to_c n = Church (\f c -> iterate f c !! n)

...或者,如果您确实进行了绑定,请在Church构造函数中进行,因为那里的环境已经是多态的:

to_c n = Church (let fn f c = iterate f c !! n in fn)
于 2017-12-30T16:59:00.867 回答