首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何为ListIsomorphic创建Vector.Unboxed实例?

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

Stack Overflow用户
提问于 2015-08-21 02:13:48
回答 1查看 56关注 0票数 1

由于 instance for generic vectors似乎是不可能的(或者不是一个好主意),所以我试图直接为Vector.Unboxed编写一个。

代码语言:javascript
复制
class ListIsomorphic l where
    toList    :: l a -> [a]
    fromList  :: [a] -> l a

instance ListIsomorphic UV.Vector where
    toList   = UV.toList
    fromList = UV.fromList

我得到了以下错误:

代码语言:javascript
复制
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’

我试过遵循编译器错误建议,但没有成功。我怎么写呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-21 03:15:34

您不能。您的ListIsomorphic类保证fromList可以应用于任何类型的a。但是,未装箱向量要求aUnbox的一个实例。

您可以编写一个类ListIsomorphicUnboxed,该类包含:

代码语言:javascript
复制
class ListIsomorphicUnboxed l where
    fromListUnboxed :: (Unbox a) => [a] -> l a
    toListUnboxed :: (Unbox a) => l a -> [a]

另一种方法可以是使用约束(您需要添加一些语言扩展):

代码语言:javascript
复制
{-# 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

(代码未经测试!)

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32131352

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档