让重命名函数中断代码

时间:2014-07-13 16:19:22

标签: haskell ghc

在将代码迭代到正确的版本时,我遇到了以下好奇心:

{-# LANGUAGE RankNTypes #-}

module Foo where

import Data.Vector.Generic.Mutable as M
import Control.Monad.Primitive

-- an in-place vector function with dimension
data DimFun v m r = 
  DimFun Int (v (PrimState m) r -> m ())

eval :: (PrimMonad m, MVector v r) => DimFun v m r -> v (PrimState m) r -> m ()
eval = error ""

iterateFunc :: (PrimMonad m, MVector v r)
            => (forall v' . (MVector v' r) => DimFun v' m r) -> DimFun v m r
iterateFunc = error ""

f :: (PrimMonad m, MVector v r)
      => DimFun v m r
f = error ""

iteratedF :: (MVector v r, PrimMonad m) 
           => v (PrimState m) r -> m ()
iteratedF y = 
    let f' = f
    in eval (iterateFunc f') y

此代码无法编译:

Testing/Foo.hs:87:14:
    Could not deduce (MVector v0 r) arising from a use of ‘f’
    from the context (MVector v r, PrimMonad m)
      bound by the type signature for
                 iteratedF :: (MVector v r, PrimMonad m) =>
                              v (PrimState m) r -> m ()
      at Testing/Foo.hs:(84,14)-(85,39)
    The type variable ‘v0’ is ambiguous
    Relevant bindings include
      f' :: DimFun v0 m r (bound at Testing/Foo.hs:87:9)
      y :: v (PrimState m) r (bound at Testing/Foo.hs:86:11)
      iteratedF :: v (PrimState m) r -> m ()
        (bound at Testing/Foo.hs:86:1)
    In the expression: f
    In an equation for ‘f'’: f' = f
    In the expression: let f' = f in eval (iterateFunc f') y

Testing/Foo.hs:88:26:
    Couldn't match type ‘v0’ with ‘v'’
      because type variable ‘v'’ would escape its scope
    This (rigid, skolem) type variable is bound by
      a type expected by the context: MVector v' r => DimFun v' m r
      at Testing/Foo.hs:88:14-27
    Expected type: DimFun v' m r
      Actual type: DimFun v0 m r
    Relevant bindings include
      f' :: DimFun v0 m r (bound at Testing/Foo.hs:87:9)
    In the first argument of ‘iterateFunc’, namely ‘f'’
    In the first argument of ‘eval’, namely ‘(iterateFunc f')’
Failed, modules loaded: none.

但是,如果我将iteratedF的定义更改为

iteratedF y = eval (iterateFunc f) y

代码编译为GHC 7.8.2。这个问题不是关于看起来很奇怪的签名或数据类型,只是这样:为什么将f重命名为f'会破坏代码?这似乎对我来说是一个错误。

2 个答案:

答案 0 :(得分:12)

禁用单态限制,我可以编译你的代码。所以,只需添加

{-# LANGUAGE NoMonomorphismRestriction #-}

在文件的开头。

类型错误的原因是定义

let f' = f

不使用函数模式(例如f' x y = ...),因此单态限制启动并强制f'为单态,而iterateFunc需要多态函数。

或者,添加类型注释

let f' :: (PrimMonad m, MVector v r) => DimFun v m r
    f' = f

答案 1 :(得分:7)

问题当然不是重命名,而是绑定到新变量。由于iterateFunc是Rank-2,因此需要多态参数函数。当然,f中的v是多态的,因此可以使用它。但是当你写f' = f时,不清楚f'应该是什么类型:与f相同的多态类型,或者某种单态类型,可能与{{{}中的另一个类型变量有某种关系。 1}}编译器尚未推断出。

编译器默认为单态选项;正如chi所说,这是单态限制的错误,所以如果你把它关闭,你的代码实际上是编译的。

然而,即使没有iteratedF代码中的单态限制,同样的问题也会出现,它无法完全避免。唯一可靠的解决方案是本地签名,通常需要RankNTypes