简体   繁体   English

使用Data.Vector.Generic接口

[英]Using the Data.Vector.Generic interface

I'm having some trouble defining the type signature when using the generic vector interface. 在使用通用矢量接口时,我在定义类型签名时遇到了一些麻烦。 I want to construct a method that can work on both boxed and unboxed vectors. 我想构建一个可以处理盒装和非盒装载体的方法。

This works, but is constrained to boxed vectors: 这有效,但受限于盒装向量:

import           Control.Monad.ST
import           Data.Vector                 as V
import           Data.Vector.Generic         as VG
import           Data.Vector.Generic.Mutable as VGM
import           Data.Vector.Mutable         as VM
import           Data.Vector.Unboxed         as VU
import           Data.Vector.Unboxed.Mutable as VUM

mySwap :: V.Vector a -> V.Vector a
mySwap vec = runST $ do
  vec_mut <- V.thaw vec
  VM.swap vec_mut 0 1
  V.unsafeFreeze vec_mut

If I change V to VG in order to use the generic interface, then two arguments are needed for the vector in the type signature, but I'm not sure how to constrain the first argument: 如果我将V更改为VG以便使用通用接口,那么类型签名中的向量需要两个参数,但我不确定如何约束第一个参数:

mySwap2 :: VG.Vector v a -> VG.Vector v a
mySwap2 vec = runST $ do
  vec_mut <- VG.thaw vec
  VGM.swap vec_mut 0 1
  VG.unsafeFreeze vec_mut

Expected a type, but VG.Vector va has kind ghc-prim-.4.0.0:GHC.Prim.Constraint 期望一个类型,但VG.Vector va有种ghc-prim-.4.0.0:GHC.Prim.Constraint

I just removed the type signature and let GHC guide me: 我刚刚删除了类型签名,让GHC指导我:

gswap v = runST $ do
  vmut <- VG.thaw v
  VGM.swap vmut 0 1
  VG.unsafeFreeze vmut

At first this yielded: 起初这产生了:

Illegal equational constraint Mutable v ~ Mutable v
(Use GADTs or TypeFamilies to permit this)

After adding LANGUAGE TypeFamilies it compiled and :t gswap returned: 添加LANGUAGE TypeFamilies它编译并:t gswap返回:

gswap
  :: (VG.Vector v a, VG.Vector v1 a, Mutable v1 ~ Mutable v) =>
     v a -> v1 a

But if v and v1 are the same type the mutable constraint is trivially satisfied and you don't need the TypeFamilies extension. 但是如果vv1是相同的类型,则可以简单地满足可变约束,并且您不需要TypeFamilies扩展。

In the Generic module, Vector is a type class and needs to be used as a constraint, eg: Generic模块中, Vector是一个类型类,需要用作约束,例如:

mySwap2 :: VG.Vector v a => v a -> v a

This means: v is some kind of vector which is capable of holding a s. 这意味着: v是某种载体,其能够保持的a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM