由于 instance for generic vectors似乎是不可能的(或者不是一个好主意),所以我试图直接为Vector.Unboxed编写一个。
class ListIsomorphic l where
toList :: l a -> [a]
fromList :: [a] -> l a
instance ListIsomorphic UV.Vector where
toList = UV.toList
fromList = UV.fromList我得到了以下错误:
test.hs:70:14:
No instance for (UV.Unbox a) arising from a use of ‘UV.toList’
Possible fix:
add (UV.Unbox a) to the context of
the type signature for toList :: UV.Vector a -> [a]
In the expression: UV.toList
In an equation for ‘toList’: toList = UV.toList
In the instance declaration for ‘ListIsomorphic UV.Vector’
test.hs:71:16:
No instance for (UV.Unbox a) arising from a use of ‘UV.fromList’
Possible fix:
add (UV.Unbox a) to the context of
the type signature for fromList :: [a] -> UV.Vector a
In the expression: UV.fromList
In an equation for ‘fromList’: fromList = UV.fromList
In the instance declaration for ‘ListIsomorphic UV.Vector’我试过遵循编译器错误建议,但没有成功。我怎么写呢?
发布于 2015-08-21 03:15:34
您不能。您的ListIsomorphic类保证fromList可以应用于任何类型的a。但是,未装箱向量要求a是Unbox的一个实例。
您可以编写一个类ListIsomorphicUnboxed,该类包含:
class ListIsomorphicUnboxed l where
fromListUnboxed :: (Unbox a) => [a] -> l a
toListUnboxed :: (Unbox a) => l a -> [a]另一种方法可以是使用约束(您需要添加一些语言扩展):
{-# LANGUAGE ConstraintKinds, TypeFamilies #-}
import GHC.Exts (Constraint)
class ListIsomorphic l where
type C l a :: Constraint
type C l a = () -- default to no constraint
fromList :: C l a => [a] -> l a
toList :: C l a => l a -> [a]
instance ListIsomorphic UV.Vector where
type C UV.Vector a = UV.Unbox a
toList = UV.toList
fromList = UV.fromList(代码未经测试!)
这样,每个实例都可以有不同的约束。然而,这并不是一个非常普遍的解决方案。
https://stackoverflow.com/questions/32131352
复制相似问题