簡體   English   中英

如何為Vector.Unboxed創建ListIsomorphic實例?

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

由於似乎不可能為通用向量編寫ListIsomorphic實例 (或不是一個好主意),因此我試圖直接為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類承諾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

(代碼未經測試!)

這樣,每個實例可以具有不同的約束。 但是,這不是很常見的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM