如何为 Vector.Unboxed 创建一个 ListIsomorphic 实例?

How do I create a ListIsomorphic instance for Vector.Unboxed?

既然 似乎是不可能的(或者不是一个好主意),我试图直接为 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’

我已经尝试按照编译器错误建议进行操作,但没有成功。怎么写呢?

你不能。您的 ListIsomorphic class 承诺 fromList 可以应用于 任何 类型 a。但是,未装箱的向量要求 aUnbox.

的实例

您可以改为编写 class 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

(代码未经测试!)

这样每个实例都可以有不同的约束。然而,这不是一个很常见的解决方案。