gpt4 book ai didi

haskell - 让重命名函数破坏代码

转载 作者:行者123 更新时间:2023-12-03 15:30:31 24 4
gpt4 key购买 nike

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

{-# 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 编译。这个问题与看起来很奇怪的签名或数据类型无关,它只是这样:为什么重命名 ff'破解密码?这对我来说似乎是一个错误。

最佳答案

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

{-# LANGUAGE NoMonomorphismRestriction #-}

在文件的开头。

类型错误的原因是定义
let f' = f

不使用函数模式(例如 f' x y = ... ),因此单态限制开始生效并强制 f'是单态的,而 iterateFunc需要一个多态函数。

或者,添加类型注释
let f' :: (PrimMonad m, MVector v r) => DimFun v m r
f' = f

关于haskell - 让重命名函数破坏代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24724738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com