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

时间:2015-08-21 02:13:48

标签: haskell vector typeclass

由于writing a ListIsomorphic 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’

我已经尝试过遵循编译器错误建议,但它没有用。我怎么写呢?

1 个答案:

答案 0 :(得分:2)

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

您可以改为编写一个具有以下内容的类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

(代码未经测试!)

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